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

interface Props {
  onClose: () => void;
  onSave: (record: TerminationRecord) => void;
}

const employees = [
  { name: 'Sarah Kamau', id: 'EMP-042', dept: 'Finance', position: 'Finance Officer' },
  { name: 'James Otieno', id: 'EMP-017', dept: 'IT', position: 'Systems Administrator' },
  { name: 'Peter Mwangi', id: 'EMP-033', dept: 'Operations', position: 'Field Officer' },
  { name: 'Lydia Achieng', id: 'EMP-058', dept: 'HR', position: 'HR Assistant' },
  { name: 'Francis Njiru', id: 'EMP-009', dept: 'Programs', position: 'Program Coordinator' },
  { name: 'Christine Owino', id: 'EMP-071', dept: 'Finance', position: 'Accounts Payable Clerk' },
  { name: 'Kevin Mutua', id: 'EMP-024', dept: 'IT', position: 'Network Technician' },
  { name: 'Mary Auma', id: 'EMP-003', dept: 'Admin', position: 'Office Manager' },
  { name: 'John Kariuki', id: 'EMP-055', dept: 'Legal', position: 'Legal Officer' },
  { name: 'Alice Muthoni', id: 'EMP-061', dept: 'Programs', position: 'M&E Officer' },
];

export default function NewTerminationModal({ onClose, onSave }: Props) {
  const [empSearch, setEmpSearch] = useState('');
  const [selectedEmp, setSelectedEmp] = useState<typeof employees[0] | null>(null);
  const [showEmpDropdown, setShowEmpDropdown] = useState(false);
  const [terminationDate, setTerminationDate] = useState('');
  const [category, setCategory] = useState<TerminationCategory | ''>('');
  const [reason, setReason] = useState<TerminationReason | ''>('');
  const [file, setFile] = useState<File | null>(null);
  const [fileError, setFileError] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const [newCaseNo, setNewCaseNo] = useState('');

  const filteredEmps = employees.filter(e =>
    e.name.toLowerCase().includes(empSearch.toLowerCase()) || e.id.toLowerCase().includes(empSearch.toLowerCase())
  );

  const reasonsForCategory = TERMINATION_REASONS.filter(r => !category || r.category === category);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const allowed = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png'];
    if (!allowed.includes(f.type)) { setFileError('Only PDF, DOC, DOCX, JPG, PNG allowed.'); return; }
    if (f.size > 5 * 1024 * 1024) { setFileError('File must be under 5MB.'); return; }
    setFileError('');
    setFile(f);
  };

  const handleSubmit = () => {
    if (!selectedEmp || !terminationDate || !category || !reason) return;
    const caseNo = `TRM-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 900) + 100)}`;
    setNewCaseNo(caseNo);
    const record: TerminationRecord = {
      id: `TRM-${Date.now()}`,
      caseNo,
      employeeId: selectedEmp.id,
      employeeName: selectedEmp.name,
      department: selectedEmp.dept,
      position: selectedEmp.position,
      terminationDate,
      category: category as TerminationCategory,
      reason: reason as TerminationReason,
      supportingLetter: file ? file.name : undefined,
      initiatedDate: new Date().toISOString().split('T')[0],
      initiatedBy: 'HR Admin',
      source: 'hr',
    };
    onSave(record);
    setSubmitted(true);
  };

  const canSubmit = selectedEmp && terminationDate && category && reason;

  if (submitted) {
    return (
      <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl p-8 w-full max-w-md text-center shadow-2xl">
          <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style={{ background: '#fdf0fc' }}>
            <i className="ri-checkbox-circle-fill text-4xl" style={{ color: '#b828a0' }}></i>
          </div>
          <h3 className="text-xl font-bold text-gray-800 mb-2">Termination Recorded</h3>
          <p className="text-gray-500 text-sm mb-1">Case No: <span className="font-semibold text-gray-700">{newCaseNo}</span></p>
          <p className="text-gray-500 text-sm mb-6">The termination has been added to the register. Employee status updated to Terminated.</p>
          <button onClick={onClose} className="px-6 py-2.5 rounded-xl text-white font-semibold cursor-pointer" style={{ background: '#b828a0' }}>Done</button>
        </div>
      </div>
    );
  }

  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-xl 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">Initiate Termination</h2>
            <p className="text-xs text-gray-500">HR Admin — Direct termination record</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-5">
          <div className="p-3 rounded-xl bg-amber-50 border border-amber-200 flex gap-2">
            <div className="w-5 h-5 flex items-center justify-center flex-shrink-0 mt-0.5">
              <i className="ri-information-line text-amber-600"></i>
            </div>
            <p className="text-xs text-amber-800">Termination ends here. No clearance, exit interview, or legal hold required. The record will be added directly to the register.</p>
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1">Employee Search *</label>
            <div className="relative">
              <input
                value={selectedEmp ? `${selectedEmp.name} (${selectedEmp.id})` : empSearch}
                onChange={e => { setEmpSearch(e.target.value); setSelectedEmp(null); setShowEmpDropdown(true); }}
                onFocus={() => setShowEmpDropdown(true)}
                placeholder="Search by name or ID…"
                className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-pink-400"
              />
              {showEmpDropdown && !selectedEmp && filteredEmps.length > 0 && (
                <div className="absolute top-full left-0 right-0 bg-white border border-gray-200 rounded-lg shadow-lg z-10 max-h-48 overflow-y-auto mt-1">
                  {filteredEmps.map(e => (
                    <button key={e.id} onClick={() => { setSelectedEmp(e); setEmpSearch(''); setShowEmpDropdown(false); }}
                      className="w-full text-left px-4 py-2.5 hover:bg-pink-50 cursor-pointer border-b border-gray-50 last:border-0">
                      <p className="text-sm font-medium text-gray-800">{e.name}</p>
                      <p className="text-xs text-gray-400">{e.id} · {e.dept} · {e.position}</p>
                    </button>
                  ))}
                </div>
              )}
            </div>
            {selectedEmp && (
              <div className="mt-2 p-3 bg-gray-50 rounded-lg flex items-center justify-between">
                <div>
                  <p className="text-sm font-semibold text-gray-800">{selectedEmp.name}</p>
                  <p className="text-xs text-gray-500">{selectedEmp.id} · {selectedEmp.dept} · {selectedEmp.position}</p>
                </div>
                <button onClick={() => setSelectedEmp(null)} className="text-gray-400 hover:text-red-500 cursor-pointer">
                  <div className="w-5 h-5 flex items-center justify-center"><i className="ri-close-line"></i></div>
                </button>
              </div>
            )}
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1">Termination Date *</label>
            <input type="date" value={terminationDate} onChange={e => setTerminationDate(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-2">Termination Category *</label>
            <div className="flex gap-3">
              {(['Voluntary', 'Involuntary', 'Other'] as TerminationCategory[]).map(c => (
                <button key={c} onClick={() => { setCategory(c); setReason(''); }}
                  className={`flex-1 py-2.5 rounded-lg text-sm font-medium border cursor-pointer whitespace-nowrap transition-all ${category === c ? 'text-white border-transparent' : 'bg-white border-gray-200 text-gray-600 hover:border-pink-300'}`}
                  style={category === c ? { background: '#b828a0' } : {}}>
                  {c}
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1">Termination Reason *</label>
            <div className="grid grid-cols-2 gap-2">
              {TERMINATION_REASONS.filter(r => !category || r.category === category).map(r => (
                <button key={r.reason} onClick={() => setReason(r.reason)}
                  className={`py-2 px-3 rounded-lg text-xs font-medium border cursor-pointer whitespace-nowrap text-left transition-all ${reason === r.reason ? 'text-white border-transparent' : 'bg-white border-gray-200 text-gray-600 hover:border-pink-300'}`}
                  style={reason === r.reason ? { background: '#8b5cf6' } : {}}>
                  {r.reason}
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-gray-600 mb-1">Resignation / Supporting Letter</label>
            <div className="border-2 border-dashed border-gray-200 rounded-xl p-4 text-center hover:border-pink-300 transition-colors">
              <input type="file" id="termFile" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" onChange={handleFileChange} className="hidden" />
              <label htmlFor="termFile" className="cursor-pointer">
                <div className="w-8 h-8 flex items-center justify-center mx-auto mb-2">
                  <i className="ri-upload-cloud-line text-2xl text-gray-400"></i>
                </div>
                {file ? (
                  <p className="text-sm font-medium text-green-700">{file.name}</p>
                ) : (
                  <>
                    <p className="text-sm text-gray-500">Click to upload or drag & drop</p>
                    <p className="text-xs text-gray-400 mt-1">PDF, DOC, DOCX, JPG, PNG — max 5MB</p>
                  </>
                )}
              </label>
            </div>
            {fileError && <p className="text-xs text-red-500 mt-1">{fileError}</p>}
          </div>
        </div>

        <div className="px-6 py-4 border-t border-gray-100 flex justify-between">
          <button onClick={onClose}
            className="px-4 py-2 rounded-lg border border-gray-200 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
            Cancel
          </button>
          <button onClick={handleSubmit} disabled={!canSubmit}
            className="px-6 py-2 rounded-lg text-white text-sm font-semibold cursor-pointer whitespace-nowrap shadow disabled:opacity-50"
            style={{ background: '#b828a0' }}>
            Confirm Termination
          </button>
        </div>
      </div>
    </div>
  );
}
