'use client';
import { useState } from 'react';
import { TrainingRequest, RequestStatus, ApprovalStage } from './trainingModuleData';
import { useTrainingStore } from '../../../lib/trainingStore';
import { initialPrograms } from './trainingData';

const BRAND = '#B22698';

const STAGE_CONFIG: Record<string, { label: string; color: string; bg: string; icon: string }> = {
  HR: { label: 'Awaiting HR', color: '#d97706', bg: '#fef3c7', icon: 'ri-user-settings-line' },
  HOS: { label: 'Awaiting HOS', color: BRAND, bg: '#fce7f3', icon: 'ri-building-line' },
  Finance: { label: 'Awaiting Finance', color: '#065f46', bg: '#d1fae5', icon: 'ri-money-dollar-circle-line' },
  Complete: { label: 'Fully Approved', color: '#16a34a', bg: '#dcfce7', icon: 'ri-checkbox-circle-line' },
  Rejected: { label: 'Rejected', color: '#dc2626', bg: '#fee2e2', icon: 'ri-close-circle-line' },
};

const APPROVAL_STEPS = [
  { stage: 'HR' as ApprovalStage, label: 'HR Manager', icon: 'ri-user-settings-line', nextStage: 'HOS' as ApprovalStage, nextStatus: 'HR Approved' as RequestStatus },
  { stage: 'HOS' as ApprovalStage, label: 'Head of Secretariat', icon: 'ri-building-line', nextStage: 'Finance' as ApprovalStage, nextStatus: 'HOS Approved' as RequestStatus },
  { stage: 'Finance' as ApprovalStage, label: 'Finance Officer', icon: 'ri-money-dollar-circle-line', nextStage: 'Complete' as ApprovalStage, nextStatus: 'Finance Approved' as RequestStatus },
];

export default function TrainingNeedsTab() {
  const { trainingReqs, updateTrainingReqs } = useTrainingStore();
  const [requests, setRequests] = useState<TrainingRequest[]>(trainingReqs);
  const [search, setSearch] = useState('');
  const [stageFilter, setStageFilter] = useState<string>('all');
  const [rejectModal, setRejectModal] = useState<TrainingRequest | null>(null);
  const [assignModal, setAssignModal] = useState<TrainingRequest | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [selectedProgram, setSelectedProgram] = useState('');
  const [toast, setToast] = useState('');

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3000); };

  const today = new Date().toISOString().split('T')[0];

  const filtered = requests.filter(r => {
    const ms = stageFilter === 'all' || r.currentStage === stageFilter;
    const mq = !search || r.employeeName.toLowerCase().includes(search.toLowerCase()) ||
      r.courseRequested.toLowerCase().includes(search.toLowerCase()) ||
      r.dept.toLowerCase().includes(search.toLowerCase());
    return ms && mq;
  });

  // HR portal: only show requests currently awaiting HR approval, plus processed ones
  const pending = filtered.filter(r => r.currentStage === 'HR');
  const processed = filtered.filter(r => r.currentStage === 'Complete' || r.currentStage === 'Rejected');

  const handleApprove = (req: TrainingRequest) => {
    if (req.currentStage !== 'HR') {
      showToast(`This request is at "${STAGE_CONFIG[req.currentStage]?.label || req.currentStage}" stage. HR can only approve "Awaiting HR" requests once.`);
      return;
    }
    // HR can only approve HR-related requests (non-HOD, non-HOS, non-Finance)
    const isHODRequest = req.employeeId.startsWith('HOD-') || req.dept === 'Management';
    const isHOSRequest = req.employeeId.startsWith('HOS-') || req.dept === 'Secretariat' || req.dept === 'Executive';
    const isFinanceRequest = req.employeeId.startsWith('FIN-') || req.dept === 'Finance';
    if (isHODRequest || isHOSRequest || isFinanceRequest) {
      showToast('This request must be approved in the respective portal (HOD / HOS / Finance).');
      return;
    }
    setAssignModal(req);
    setSelectedProgram('');
  };

  const handleRejectAttempt = (req: TrainingRequest) => {
    if (req.currentStage !== 'HR') {
      showToast(`Cannot reject: request is already at "${STAGE_CONFIG[req.currentStage]?.label || req.currentStage}" stage.`);
      return;
    }
    const isHODRequest = req.employeeId.startsWith('HOD-') || req.dept === 'Management';
    const isHOSRequest = req.employeeId.startsWith('HOS-') || req.dept === 'Secretariat' || req.dept === 'Executive';
    const isFinanceRequest = req.employeeId.startsWith('FIN-') || req.dept === 'Finance';
    if (isHODRequest || isHOSRequest || isFinanceRequest) {
      showToast('This request must be rejected in the respective portal (HOD / HOS / Finance).');
      return;
    }
    setRejectModal(req);
    setRejectReason('');
  };

  const advanceStage = (req: TrainingRequest, programId?: string) => {
    const step = APPROVAL_STEPS.find(s => s.stage === req.currentStage);
    if (!step) return;

    const approvalFields: Partial<TrainingRequest> = {};
    if (req.currentStage === 'HR') {
      approvalFields.hrApprovedBy = 'HR Manager';
      approvalFields.hrApprovedOn = today;
    } else if (req.currentStage === 'HOS') {
      approvalFields.hosApprovedBy = 'Head of Secretariat';
      approvalFields.hosApprovedOn = today;
    } else if (req.currentStage === 'Finance') {
      approvalFields.financeApprovedBy = 'Finance Officer';
      approvalFields.financeApprovedOn = today;
    }

    const updater = (prev: TrainingRequest[]) => prev.map(r => r.id === req.id ? {
      ...r,
      ...approvalFields,
      status: step.nextStatus,
      currentStage: step.nextStage,
      assignedProgramId: programId || r.assignedProgramId,
    } : r);
    setRequests(updater);
    updateTrainingReqs(updater);

    const stageLabel = STAGE_CONFIG[step.nextStage]?.label || step.nextStage;
    showToast(`Approved by ${step.label}. Now forwarded to ${stageLabel}.`);
    setAssignModal(null);
  };

  const confirmReject = () => {
    if (!rejectModal || !rejectReason.trim()) return;
    const rejectUpdater = (prev: TrainingRequest[]) => prev.map(r => r.id === rejectModal.id ? {
      ...r,
      status: 'Rejected' as RequestStatus,
      currentStage: 'Rejected' as ApprovalStage,
      rejectReason,
      rejectedBy: STAGE_CONFIG[rejectModal.currentStage]?.label || rejectModal.currentStage,
      rejectedStage: rejectModal.currentStage,
    } : r);
    setRequests(rejectUpdater);
    updateTrainingReqs(rejectUpdater);
    showToast('Request rejected. Employee notified with reason.');
    setRejectModal(null);
    setRejectReason('');
  };

  const stageCounts = APPROVAL_STEPS.reduce((acc, s) => {
    acc[s.stage] = requests.filter(r => r.currentStage === s.stage).length;
    return acc;
  }, {} as Record<string, number>);

  return (
    <div className="space-y-5">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg text-sm font-medium">{toast}</div>
      )}

      <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
        <p className="text-xs font-semibold text-gray-500 uppercase mb-3">3-Stage Approval Workflow (No CEO)</p>
        <div className="flex items-center gap-2 flex-wrap">
          {APPROVAL_STEPS.map((step, idx) => {
            const cfg = STAGE_CONFIG[step.stage];
            const count = stageCounts[step.stage] || 0;
            return (
              <div key={step.stage} className="flex items-center gap-2">
                <div className="flex items-center gap-2 px-3 py-2 rounded-xl border" style={{ borderColor: cfg.color + '40', background: cfg.bg }}>
                  <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: cfg.color }}>
                    {idx + 1}
                  </div>
                  <div>
                    <p className="text-xs font-semibold" style={{ color: cfg.color }}>{step.label}</p>
                    {count > 0 && <p className="text-xs" style={{ color: cfg.color }}>{count} pending</p>}
                  </div>
                </div>
                {idx < APPROVAL_STEPS.length - 1 && (
                  <i className="ri-arrow-right-line text-gray-300"></i>
                )}
              </div>
            );
          })}
          <i className="ri-arrow-right-line text-gray-300"></i>
          <div className="flex items-center gap-2 px-3 py-2 rounded-xl border border-green-200 bg-green-50">
            <i className="ri-checkbox-circle-line text-green-600"></i>
            <p className="text-xs font-semibold text-green-700">Fully Approved</p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4">
        {APPROVAL_STEPS.filter(s => s.stage === 'HR').map(step => {
          const cfg = STAGE_CONFIG[step.stage];
          const count = stageCounts[step.stage] || 0;
          return (
            <div key={step.stage} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center mb-3" style={{ background: cfg.bg }}>
                <i className={`${step.icon} text-lg`} style={{ color: cfg.color }}></i>
              </div>
              <p className="text-2xl font-bold text-gray-800">{count}</p>
              <p className="text-sm text-gray-500 mt-0.5">{cfg.label}</p>
            </div>
          );
        })}
        <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
          <div className="w-10 h-10 rounded-xl flex items-center justify-center mb-3" style={{ background: '#dcfce7' }}>
            <i className="ri-checkbox-circle-line text-lg text-green-600"></i>
          </div>
          <p className="text-2xl font-bold text-gray-800">{processed.length}</p>
          <p className="text-sm text-gray-500 mt-0.5">Processed</p>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100">
        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between flex-wrap gap-3">
          <div>
            <h3 className="font-semibold text-gray-800">Training Requests — Approval Queue</h3>
            <p className="text-xs text-gray-400 mt-0.5">{pending.length} request(s) awaiting action</p>
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            <div className="relative">
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search requests..."
                className="bg-gray-50 border border-gray-200 rounded-lg px-4 py-1.5 text-sm w-48 outline-none" />
              <div className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2">
                <i className="ri-search-line text-gray-400 text-sm"></i>
              </div>
            </div>
            <div className="relative">
              <select value={stageFilter} onChange={e => setStageFilter(e.target.value)}
                className="border border-gray-200 rounded-lg px-3 py-1.5 text-sm outline-none cursor-pointer pr-8 bg-white appearance-none">
                <option value="all">All Stages</option>
                <option value="HR">Awaiting HR</option>
                <option value="Complete">Fully Approved</option>
                <option value="Rejected">Rejected</option>
              </select>
              <div className="w-4 h-4 flex items-center justify-center absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none">
                <i className="ri-arrow-down-s-line text-gray-400 text-sm"></i>
              </div>
            </div>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                {['Request ID', 'Employee', 'Course Requested', 'Justification', 'Estimated Cost', 'Date Submitted', 'Current Stage', 'Actions'].map(h => (
                  <th key={h} className="text-left text-xs font-semibold text-gray-500 px-4 py-3 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {pending.map(r => {
                const cfg = STAGE_CONFIG[r.currentStage] || STAGE_CONFIG['HR'];
                const step = APPROVAL_STEPS.find(s => s.stage === r.currentStage);
                return (
                  <tr key={r.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3 text-xs font-mono font-semibold text-gray-600">{r.id}</td>
                    <td className="px-4 py-3">
                      <p className="text-sm font-medium text-gray-800">{r.employeeName}</p>
                      <p className="text-xs text-gray-400">{r.dept}</p>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-700 max-w-[180px]">
                      <p className="truncate font-medium">{r.courseRequested}</p>
                      <p className="text-xs text-gray-400">{r.preferredStartDate} → {r.preferredEndDate}</p>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-600 max-w-[200px]">
                      <p className="line-clamp-2">{r.justification}</p>
                    </td>
                    <td className="px-4 py-3 text-sm font-semibold text-gray-800">KES {r.estimatedCost.toLocaleString()}</td>
                    <td className="px-4 py-3 text-sm text-gray-600">{r.dateSubmitted}</td>
                    <td className="px-4 py-3">
                      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold"
                        style={{ color: cfg.color, background: cfg.bg }}>
                        <i className={cfg.icon}></i>
                        {cfg.label}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        {step && (
                          <button onClick={() => handleApprove(r)}
                            className="text-xs px-3 py-1.5 rounded-lg cursor-pointer font-semibold text-white whitespace-nowrap hover:opacity-80"
                            style={{ background: '#16a34a' }}>
                            Approve
                          </button>
                        )}
                        <button onClick={() => handleRejectAttempt(r)}
                          className="text-xs px-3 py-1.5 rounded-lg cursor-pointer font-semibold text-white whitespace-nowrap hover:opacity-80 bg-red-500">
                          Reject
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
              {pending.length === 0 && (
                <tr>
                  <td colSpan={8} className="text-center py-12 text-gray-400 text-sm">
                    <div className="w-10 h-10 flex items-center justify-center mx-auto mb-2">
                      <i className="ri-checkbox-circle-line text-3xl text-green-300"></i>
                    </div>
                    No pending requests — all caught up!
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {processed.length > 0 && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100">
          <div className="px-5 py-4 border-b border-gray-100">
            <h3 className="font-semibold text-gray-800">Processed Requests</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-100">
                  {['Request ID', 'Employee', 'Course Requested', 'Estimated Cost', 'Date Submitted', 'Final Status', 'Approval Trail', 'Note'].map(h => (
                    <th key={h} className="text-left text-xs font-semibold text-gray-500 px-4 py-3 whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {processed.map(r => {
                  const cfg = STAGE_CONFIG[r.currentStage] || STAGE_CONFIG['Rejected'];
                  return (
                    <tr key={r.id} className="border-b border-gray-50 hover:bg-gray-50">
                      <td className="px-4 py-3 text-xs font-mono font-semibold text-gray-600">{r.id}</td>
                      <td className="px-4 py-3">
                        <p className="text-sm font-medium text-gray-800">{r.employeeName}</p>
                        <p className="text-xs text-gray-400">{r.dept}</p>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-700 max-w-[180px]">
                        <p className="truncate">{r.courseRequested}</p>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600">KES {r.estimatedCost.toLocaleString()}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{r.dateSubmitted}</td>
                      <td className="px-4 py-3">
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold"
                          style={{ color: cfg.color, background: cfg.bg }}>
                          <i className={cfg.icon}></i>
                          {r.currentStage === 'Complete' ? 'Fully Approved' : 'Rejected'}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-1 flex-wrap">
                          {r.hrApprovedOn && <span className="text-xs bg-yellow-100 text-yellow-700 px-1.5 py-0.5 rounded">HR ✓</span>}
                          {r.hosApprovedOn && <span className="text-xs bg-pink-100 text-pink-700 px-1.5 py-0.5 rounded">HOS ✓</span>}
                          {r.financeApprovedOn && <span className="text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded">Finance ✓</span>}
                          {r.currentStage === 'Rejected' && (
                            <span className="text-xs bg-red-100 text-red-700 px-1.5 py-0.5 rounded">Rejected at {r.rejectedStage}</span>
                          )}
                        </div>
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-500 max-w-[180px]">
                        {r.currentStage === 'Complete' && r.assignedProgramId ? (
                          <span className="text-green-600">Assigned to {r.assignedProgramId}</span>
                        ) : r.rejectReason ? (
                          <span className="text-red-500 line-clamp-2">{r.rejectReason}</span>
                        ) : '—'}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {rejectModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-red-50">
              <h2 className="font-bold text-gray-800 text-lg">Reject Training Request</h2>
              <button onClick={() => setRejectModal(null)} className="w-8 h-8 flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-gray-600 text-xl"></i>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="bg-gray-50 rounded-xl p-4">
                <p className="text-sm font-semibold text-gray-800">{rejectModal.courseRequested}</p>
                <p className="text-xs text-gray-500 mt-1">{rejectModal.employeeName} · {rejectModal.dept}</p>
                <p className="text-xs text-gray-400 mt-1">Rejecting at stage: <strong>{STAGE_CONFIG[rejectModal.currentStage]?.label}</strong></p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Reason for Rejection <span className="text-red-500">*</span></label>
                <textarea value={rejectReason} onChange={e => setRejectReason(e.target.value)}
                  rows={3} maxLength={500} placeholder="Provide a clear reason..."
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-red-400 resize-none" />
                <p className="text-xs text-gray-400 mt-1">{rejectReason.length}/500 characters</p>
              </div>
              <div className="flex gap-3">
                <button onClick={confirmReject} disabled={!rejectReason.trim()}
                  className="flex-1 py-2.5 rounded-xl bg-red-500 text-white text-sm font-semibold cursor-pointer hover:bg-red-600 disabled:opacity-50">
                  Confirm Rejection
                </button>
                <button onClick={() => setRejectModal(null)}
                  className="flex-1 py-2.5 rounded-xl border border-gray-200 text-gray-600 text-sm font-semibold cursor-pointer hover:bg-gray-50">
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {assignModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: BRAND }}>
              <h2 className="font-bold text-white text-lg">HR Approval — Step 1 of 3</h2>
              <button onClick={() => setAssignModal(null)} className="w-8 h-8 flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-white text-xl"></i>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="bg-gray-50 rounded-xl p-4">
                <p className="text-sm font-semibold text-gray-800">{assignModal.courseRequested}</p>
                <p className="text-xs text-gray-500 mt-1">{assignModal.employeeName} · {assignModal.dept}</p>
                <p className="text-xs text-gray-400 mt-1">KES {assignModal.estimatedCost.toLocaleString()}</p>
              </div>
              <div className="rounded-xl p-3" style={{ background: '#fce7f3' }}>
                <p className="text-xs font-semibold mb-2" style={{ color: BRAND }}>After HR approval, request moves to:</p>
                <div className="flex items-center gap-2">
                  <span className="text-xs font-medium" style={{ color: BRAND }}>HOS</span>
                  <i className="ri-arrow-right-line text-gray-300 text-xs"></i>
                  <span className="text-xs font-medium text-blue-600">Finance</span>
                  <i className="ri-arrow-right-line text-gray-300 text-xs"></i>
                  <span className="text-xs font-medium text-green-600">Approved</span>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Assign to Program (optional)</label>
                <div className="relative">
                  <select value={selectedProgram} onChange={e => setSelectedProgram(e.target.value)}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 appearance-none bg-white cursor-pointer">
                    <option value="">— Approve without assigning —</option>
                    {initialPrograms.filter(p => p.status !== 'Completed').map(p => (
                      <option key={p.id} value={p.id}>{p.title} ({p.start})</option>
                    ))}
                  </select>
                  <div className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
                    <i className="ri-arrow-down-s-line text-gray-400 text-sm"></i>
                  </div>
                </div>
              </div>
              <div className="flex gap-3">
                <button onClick={() => advanceStage(assignModal, selectedProgram || undefined)}
                  className="flex-1 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer hover:opacity-90"
                  style={{ background: BRAND }}>
                  Approve & Forward to HOS
                </button>
                <button onClick={() => setAssignModal(null)}
                  className="flex-1 py-2.5 rounded-xl border border-gray-200 text-gray-600 text-sm font-semibold cursor-pointer hover:bg-gray-50">
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
