'use client';
import { useState } from 'react';
import { employeeTerminationRequests, EmployeeTerminationRequest, TerminationCategory, TerminationReason, TERMINATION_REASONS } from './terminationData';

const statusColors: Record<string, string> = {
  'Pending HOD Review': 'bg-purple-100 text-purple-700',
  'Pending Manager Review': 'bg-yellow-100 text-yellow-700',
  'Pending HR Review': 'bg-blue-100 text-blue-700',
  'Approved': 'bg-green-100 text-green-700',
  'Rejected': 'bg-red-100 text-red-700',
  'Withdrawn': 'bg-gray-100 text-gray-600',
};

export default function EmployeeRequestsTab() {
  const [requests, setRequests] = useState<EmployeeTerminationRequest[]>(employeeTerminationRequests);
  const [selected, setSelected] = useState<EmployeeTerminationRequest | null>(null);
  const [hrModal, setHrModal] = useState<EmployeeTerminationRequest | null>(null);
  const [hrForm, setHrForm] = useState({ finalCategory: '' as TerminationCategory | '', finalReason: '' as TerminationReason | '', finalDate: '', comments: '' });
  const [filterStatus, setFilterStatus] = useState('All');

  const filtered = requests.filter(r => filterStatus === 'All' || r.status === filterStatus);

  const handleHRApprove = () => {
    if (!hrModal || !hrForm.finalCategory || !hrForm.finalReason || !hrForm.finalDate) return;
    setRequests(prev => prev.map(r => r.id === hrModal.id ? {
      ...r,
      status: 'Approved' as const,
      hrApprovedDate: new Date().toISOString().split('T')[0],
      hrComments: hrForm.comments,
      finalCategory: hrForm.finalCategory as TerminationCategory,
      finalReason: hrForm.finalReason as TerminationReason,
      finalTerminationDate: hrForm.finalDate,
      timeline: [...r.timeline, { step: 'HR Approved & Terminated', date: new Date().toLocaleString(), actor: 'HR Admin', note: hrForm.comments }],
    } : r));
    setHrModal(null);
    setHrForm({ finalCategory: '', finalReason: '', finalDate: '', comments: '' });
  };

  const handleHRReject = () => {
    if (!hrModal) return;
    setRequests(prev => prev.map(r => r.id === hrModal.id ? {
      ...r,
      status: 'Rejected' as const,
      hrRejectedDate: new Date().toISOString().split('T')[0],
      hrComments: hrForm.comments || 'Application rejected by HR.',
      timeline: [...r.timeline, { step: 'HR Rejected', date: new Date().toLocaleString(), actor: 'HR Admin', note: hrForm.comments || 'Application rejected by HR.' }],
    } : r));
    setHrModal(null);
  };

  const handleManagerApprove = (id: string, comments: string) => {
    setRequests(prev => prev.map(r => r.id === id ? {
      ...r,
      status: 'Pending HR Review' as const,
      managerApprovedDate: new Date().toISOString().split('T')[0],
      managerComments: comments,
      timeline: [...r.timeline, { step: 'Manager Approved', date: new Date().toLocaleString(), actor: 'Manager', note: comments }, { step: 'Pending HR Final Review', date: new Date().toLocaleString(), actor: 'System' }],
    } : r));
  };

  const handleManagerReject = (id: string, comments: string) => {
    setRequests(prev => prev.map(r => r.id === id ? {
      ...r,
      status: 'Rejected' as const,
      managerRejectedDate: new Date().toISOString().split('T')[0],
      managerComments: comments,
      timeline: [...r.timeline, { step: 'Manager Rejected', date: new Date().toLocaleString(), actor: 'Manager', note: comments }],
    } : r));
  };

  const [mgrModal, setMgrModal] = useState<EmployeeTerminationRequest | null>(null);
  const [mgrComments, setMgrComments] = useState('');

  const pendingHR = requests.filter(r => r.status === 'Pending HR Review');
  const pendingHOD = requests.filter(r => r.status === 'Pending HOD Review').length;
  const pendingMgr = requests.filter(r => r.status === 'Pending Manager Review');

  return (
    <div>
      <div className="grid grid-cols-4 gap-4 mb-6">
        {[
          { label: 'Pending HOD Review', value: pendingHOD, color: '#7c3aed' },
          { label: 'Pending Manager Review', value: pendingMgr.length, color: '#f59e0b' },
          { label: 'Pending HR Review', value: pendingHR.length, color: '#3b82f6' },
          { label: 'Total Requests', value: requests.length, color: '#b828a0' },
        ].map((s, i) => (
          <div key={i} className="bg-white rounded-xl border border-gray-200 p-4 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: s.color + '18' }}>
              <i className="ri-user-received-line text-xl" style={{ color: s.color }}></i>
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-800">{s.value}</p>
              <p className="text-xs text-gray-500">{s.label}</p>
            </div>
          </div>
        ))}
      </div>

      <div className="flex gap-2 mb-4 flex-wrap">
        {['All', 'Pending HOD Review', 'Pending Manager Review', 'Pending HR Review', 'Approved', 'Rejected'].map(s => (
          <button key={s} onClick={() => setFilterStatus(s)}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${filterStatus === s ? 'text-white border-transparent' : 'bg-white border-gray-200 text-gray-600 hover:border-pink-300'}`}
            style={filterStatus === s ? { background: '#b828a0' } : {}}>
            {s}
          </button>
        ))}
      </div>

      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-100 bg-gray-50">
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">APPLICATION ID</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">EMPLOYEE</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">SUBMITTED</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">PROPOSED LAST DAY</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">REASON</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">STATUS</th>
              <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500">ACTION</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => (
              <tr key={r.id} className="border-b border-gray-50 hover:bg-pink-50/30 transition-colors">
                <td className="px-4 py-3 font-mono text-xs text-gray-500">{r.applicationId}</td>
                <td className="px-4 py-3">
                  <p className="font-medium text-gray-800">{r.employeeName}</p>
                  <p className="text-xs text-gray-400">{r.department}</p>
                </td>
                <td className="px-4 py-3 text-xs text-gray-600">{r.submittedDate}</td>
                <td className="px-4 py-3 text-xs text-gray-600">{r.proposedLastDay}</td>
                <td className="px-4 py-3 text-xs text-gray-700">{r.reason}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${statusColors[r.status]}`}>{r.status}</span>
                </td>
                <td className="px-4 py-3 text-right">
                  <div className="flex gap-2 justify-end">
                    <button onClick={() => setSelected(r)}
                      className="px-3 py-1 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap border border-gray-200 text-gray-600 hover:bg-gray-50">
                      View
                    </button>
                    {r.status === 'Pending HR Review' && (
                      <button onClick={() => { setHrModal(r); setHrForm({ finalCategory: '', finalReason: '', finalDate: r.proposedLastDay, comments: '' }); }}
                        className="px-3 py-1 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap text-white"
                        style={{ background: '#b828a0' }}>
                        HR Review
                      </button>
                    )}
                    {r.status === 'Pending HOD Review' && (
                      <button onClick={() => { setMgrModal(r); setMgrComments(''); }}
                        className="px-3 py-1 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap text-white"
                        style={{ background: '#7c3aed' }}>
                        HOD Review
                      </button>
                    )}
                    {r.status === 'Pending Manager Review' && (
                      <button onClick={() => { setMgrModal(r); setMgrComments(''); }}
                        className="px-3 py-1 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap text-white"
                        style={{ background: '#f59e0b' }}>
                        Mgr Review
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={7} className="text-center py-10 text-gray-400">No requests found.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {selected && (
        <RequestDetailModal request={selected} onClose={() => setSelected(null)} />
      )}

      {mgrModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl overflow-hidden">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#fffbeb' }}>
              <div>
                <h2 className="text-lg font-bold text-gray-800">Manager Review</h2>
                <p className="text-xs text-gray-500">{mgrModal.employeeName} — {mgrModal.applicationId}</p>
              </div>
              <button onClick={() => setMgrModal(null)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-yellow-100 cursor-pointer">
                <i className="ri-close-line text-gray-500"></i>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-3 text-xs">
                <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Employee:</span> <span className="font-medium">{mgrModal.employeeName}</span></div>
                <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Proposed Last Day:</span> <span className="font-medium">{mgrModal.proposedLastDay}</span></div>
                <div className="bg-gray-50 rounded-lg p-3 col-span-2"><span className="text-gray-500">Reason:</span> <span className="font-medium">{mgrModal.reason}</span></div>
              </div>
              {mgrModal.documentName && (
                <div className="flex items-center gap-2 p-3 bg-blue-50 border border-blue-200 rounded-xl">
                  <div className="w-5 h-5 flex items-center justify-center"><i className="ri-file-text-line text-blue-600"></i></div>
                  <span className="text-xs text-blue-700 flex-1">{mgrModal.documentName}</span>
                  <button className="text-xs text-blue-600 underline cursor-pointer whitespace-nowrap">View</button>
                </div>
              )}
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Comments to HR</label>
                <textarea value={mgrComments} onChange={e => setMgrComments(e.target.value)} rows={3} maxLength={500}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-yellow-400 resize-none"
                  placeholder="Optional comments for HR…" />
              </div>
            </div>
            <div className="px-6 py-4 border-t border-gray-100 flex gap-3 justify-end">
              <button onClick={() => { handleManagerReject(mgrModal.id, mgrComments || 'Rejected by manager.'); setMgrModal(null); }}
                className="px-4 py-2 rounded-lg border border-red-200 text-red-600 text-sm font-medium cursor-pointer whitespace-nowrap hover:bg-red-50">
                Reject
              </button>
              <button onClick={() => { handleManagerApprove(mgrModal.id, mgrComments || 'Approved by manager.'); setMgrModal(null); }}
                className="px-6 py-2 rounded-lg text-white text-sm font-semibold cursor-pointer whitespace-nowrap shadow"
                style={{ background: '#f59e0b' }}>
                Approve & Forward to HR
              </button>
            </div>
          </div>
        </div>
      )}

      {hrModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#fdf0fc' }}>
              <div>
                <h2 className="text-lg font-bold text-gray-800">HR Final Review</h2>
                <p className="text-xs text-gray-500">{hrModal.employeeName} — {hrModal.applicationId}</p>
              </div>
              <button onClick={() => setHrModal(null)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-pink-100 cursor-pointer">
                <i className="ri-close-line text-gray-500"></i>
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-4">
              <div className="p-3 bg-green-50 border border-green-200 rounded-xl flex items-center gap-2">
                <div className="w-5 h-5 flex items-center justify-center"><i className="ri-checkbox-circle-fill text-green-600"></i></div>
                <p className="text-xs text-green-800">Manager approved on {hrModal.managerApprovedDate} — "{hrModal.managerComments}"</p>
              </div>
              <div className="grid grid-cols-2 gap-3 text-xs">
                <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Employee:</span> <span className="font-medium">{hrModal.employeeName}</span></div>
                <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Department:</span> <span className="font-medium">{hrModal.department}</span></div>
                <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Proposed Last Day:</span> <span className="font-medium">{hrModal.proposedLastDay}</span></div>
                <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Reason:</span> <span className="font-medium">{hrModal.reason}</span></div>
              </div>
              {hrModal.documentName && (
                <div className="flex items-center gap-2 p-3 bg-blue-50 border border-blue-200 rounded-xl">
                  <div className="w-5 h-5 flex items-center justify-center"><i className="ri-file-text-line text-blue-600"></i></div>
                  <span className="text-xs text-blue-700 flex-1">{hrModal.documentName}</span>
                  <button className="text-xs text-blue-600 underline cursor-pointer whitespace-nowrap">View</button>
                </div>
              )}
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-2">Final Category *</label>
                <div className="flex gap-2">
                  {(['Voluntary', 'Involuntary', 'Other'] as TerminationCategory[]).map(c => (
                    <button key={c} onClick={() => setHrForm(f => ({ ...f, finalCategory: c, finalReason: '' }))}
                      className={`flex-1 py-2 rounded-lg text-xs font-medium border cursor-pointer whitespace-nowrap ${hrForm.finalCategory === c ? 'text-white border-transparent' : 'bg-white border-gray-200 text-gray-600'}`}
                      style={hrForm.finalCategory === c ? { background: '#b828a0' } : {}}>
                      {c}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-2">Final Reason *</label>
                <div className="grid grid-cols-2 gap-2">
                  {TERMINATION_REASONS.filter(r => !hrForm.finalCategory || r.category === hrForm.finalCategory).map(r => (
                    <button key={r.reason} onClick={() => setHrForm(f => ({ ...f, finalReason: r.reason }))}
                      className={`py-2 px-3 rounded-lg text-xs font-medium border cursor-pointer text-left whitespace-nowrap ${hrForm.finalReason === r.reason ? 'text-white border-transparent' : 'bg-white border-gray-200 text-gray-600'}`}
                      style={hrForm.finalReason === r.reason ? { background: '#8b5cf6' } : {}}>
                      {r.reason}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Final Termination Date *</label>
                <input type="date" value={hrForm.finalDate} onChange={e => setHrForm(f => ({ ...f, finalDate: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-pink-400" />
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">HR Comments</label>
                <textarea value={hrForm.comments} onChange={e => setHrForm(f => ({ ...f, comments: e.target.value }))} rows={3} maxLength={500}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-pink-400 resize-none"
                  placeholder="Optional comments to employee and manager…" />
              </div>
            </div>
            <div className="px-6 py-4 border-t border-gray-100 flex gap-3 justify-end">
              <button onClick={handleHRReject}
                className="px-4 py-2 rounded-lg border border-red-200 text-red-600 text-sm font-medium cursor-pointer whitespace-nowrap hover:bg-red-50">
                Reject Application
              </button>
              <button onClick={handleHRApprove} disabled={!hrForm.finalCategory || !hrForm.finalReason || !hrForm.finalDate}
                className="px-6 py-2 rounded-lg text-white text-sm font-semibold cursor-pointer whitespace-nowrap shadow disabled:opacity-50"
                style={{ background: '#b828a0' }}>
                Approve & Terminate
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function RequestDetailModal({ request, onClose }: { request: EmployeeTerminationRequest; onClose: () => void }) {
  const statusColors: Record<string, string> = {
    'Pending Manager Review': 'bg-yellow-100 text-yellow-700',
    'Pending HR Review': 'bg-blue-100 text-blue-700',
    'Approved': 'bg-green-100 text-green-700',
    'Rejected': 'bg-red-100 text-red-700',
    'Withdrawn': 'bg-gray-100 text-gray-600',
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#fdf0fc' }}>
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="font-mono text-xs text-gray-500">{request.applicationId}</span>
              <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${statusColors[request.status]}`}>{request.status}</span>
            </div>
            <h2 className="text-lg font-bold text-gray-800">{request.employeeName}</h2>
            <p className="text-xs text-gray-500">{request.department}</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-pink-100 cursor-pointer">
            <i className="ri-close-line text-gray-500"></i>
          </button>
        </div>
        <div className="flex-1 overflow-y-auto p-6 space-y-4">
          <div className="grid grid-cols-2 gap-3 text-xs">
            <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Submitted:</span> <span className="font-medium">{request.submittedDate}</span></div>
            <div className="bg-gray-50 rounded-lg p-3"><span className="text-gray-500">Proposed Last Day:</span> <span className="font-medium">{request.proposedLastDay}</span></div>
            <div className="bg-gray-50 rounded-lg p-3 col-span-2"><span className="text-gray-500">Reason:</span> <span className="font-medium">{request.reason}{request.reasonOther ? ` — ${request.reasonOther}` : ''}</span></div>
          </div>
          {request.additionalComments && (
            <div className="bg-gray-50 rounded-xl p-3">
              <p className="text-xs font-semibold text-gray-500 mb-1">ADDITIONAL COMMENTS</p>
              <p className="text-sm text-gray-700">{request.additionalComments}</p>
            </div>
          )}
          {request.documentName && (
            <div className="flex items-center gap-2 p-3 bg-blue-50 border border-blue-200 rounded-xl">
              <div className="w-5 h-5 flex items-center justify-center"><i className="ri-file-text-line text-blue-600"></i></div>
              <span className="text-xs text-blue-700 flex-1">{request.documentName}</span>
              <button className="text-xs text-blue-600 underline cursor-pointer whitespace-nowrap">Download</button>
            </div>
          )}
          {request.managerComments && (
            <div className="p-3 bg-green-50 border border-green-200 rounded-xl">
              <p className="text-xs font-semibold text-green-700 mb-1">MANAGER DECISION ({request.managerApprovedDate || request.managerRejectedDate})</p>
              <p className="text-sm text-green-800">{request.managerComments}</p>
            </div>
          )}
          {request.hrComments && (
            <div className="p-3 bg-purple-50 border border-purple-200 rounded-xl">
              <p className="text-xs font-semibold text-purple-700 mb-1">HR DECISION ({request.hrApprovedDate || request.hrRejectedDate})</p>
              <p className="text-sm text-purple-800">{request.hrComments}</p>
            </div>
          )}
          <div>
            <p className="text-xs font-semibold text-gray-600 mb-3">APPROVAL TIMELINE</p>
            <div className="space-y-3">
              {request.timeline.map((t, i) => (
                <div key={i} className="flex gap-3">
                  <div className="flex flex-col items-center">
                    <div className="w-3 h-3 rounded-full mt-1 flex-shrink-0" style={{ background: '#b828a0' }}></div>
                    {i < request.timeline.length - 1 && <div className="w-0.5 flex-1 mt-1" style={{ background: '#e9d5f7' }}></div>}
                  </div>
                  <div className="pb-3">
                    <p className="text-sm font-semibold text-gray-800">{t.step}</p>
                    <p className="text-xs text-gray-500">{t.date} · {t.actor}</p>
                    {t.note && <p className="text-xs text-gray-600 mt-0.5 italic">"{t.note}"</p>}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="px-6 py-4 border-t border-gray-100 flex justify-end">
          <button onClick={onClose} className="px-5 py-2 rounded-lg text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>Close</button>
        </div>
      </div>
    </div>
  );
}
