'use client';
import { useState } from 'react';
import { AuthUser } from '../../../lib/authContext';
import { EmployeeTerminationRequest } from '../../hr/termination/terminationData';

const REASONS = [
  'Resignation (personal reasons)',
  'Better career opportunity',
  'Relocation',
  'Health/Medical reasons',
  'Study/Education',
  'Family reasons',
  'Other',
];

interface Props {
  user: AuthUser;
  onSubmit: (req: EmployeeTerminationRequest) => void;
  onCancel: () => void;
}

export default function EmployeeTerminationForm({ user, onSubmit, onCancel }: Props) {
  const [proposedLastDay, setProposedLastDay] = useState('');
  const [reason, setReason] = useState('');
  const [reasonOther, setReasonOther] = useState('');
  const [comments, setComments] = useState('');
  const [file, setFile] = useState<File | null>(null);
  const [fileError, setFileError] = useState('');
  const [confirmed, setConfirmed] = useState(false);
  const [errors, setErrors] = useState<string[]>([]);

  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 = (e: React.FormEvent) => {
    e.preventDefault();
    const errs: string[] = [];
    if (!proposedLastDay) errs.push('Please select your proposed last working day.');
    if (!reason) errs.push('Please select a reason for termination.');
    if (reason === 'Other' && !reasonOther.trim()) errs.push('Please specify your reason.');
    if (!file) errs.push('Please upload your resignation or supporting letter.');
    if (!confirmed) errs.push('Please confirm you understand the consequences.');
    if (errs.length > 0) { setErrors(errs); return; }
    setErrors([]);

    const appId = `APP-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 9000) + 1000)}`;
    const req: EmployeeTerminationRequest = {
      id: `ETR-${Date.now()}`,
      applicationId: appId,
      employeeId: user.employeeId || user.id,
      employeeName: user.name || 'Unknown',
      department: user.dept || 'Unknown',
      managerId: 'MGR-01',
      managerName: 'Head of Department',
      submittedDate: new Date().toISOString().split('T')[0],
      proposedLastDay,
      reason,
      reasonOther: reason === 'Other' ? reasonOther : undefined,
      additionalComments: comments || undefined,
      documentName: file?.name,
      status: 'Pending HOD Review',
      timeline: [
        { step: 'Application Submitted', date: new Date().toLocaleString(), actor: user.name || 'Unknown' },
        { step: 'HOD Notified', date: new Date().toLocaleString(), actor: 'System' },
      ],
    };
    onSubmit(req);
  };

  return (
    <div className="max-w-2xl mx-auto">
      <div className="bg-amber-50 border border-amber-300 rounded-2xl p-5 mb-6 flex gap-3">
        <div className="w-6 h-6 flex items-center justify-center flex-shrink-0 mt-0.5">
          <i className="ri-alert-line text-amber-600 text-xl"></i>
        </div>
        <div>
          <p className="font-semibold text-amber-800 mb-1">Important Notice</p>
          <p className="text-sm text-amber-700">Once submitted, your manager and HR will be notified. This action may be irreversible. Please ensure you have read and understood your employment contract and notice period requirements before proceeding.</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="p-6 border-b border-gray-100">
          <h2 className="text-lg font-bold text-gray-800">Termination Application</h2>
          <p className="text-sm text-gray-500 mt-1">Fill in all required fields and upload your supporting document.</p>
        </div>

        <div className="p-6 space-y-6">
          {errors.length > 0 && (
            <div className="bg-red-50 border border-red-200 rounded-xl p-4">
              <p className="text-sm font-semibold text-red-700 mb-2">Please fix the following:</p>
              <ul className="space-y-1">
                {errors.map((e, i) => <li key={i} className="text-xs text-red-600 flex items-center gap-1"><i className="ri-close-circle-line"></i>{e}</li>)}
              </ul>
            </div>
          )}

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Proposed Last Working Day *</label>
            <input type="date" value={proposedLastDay} onChange={e => setProposedLastDay(e.target.value)}
              min={new Date().toISOString().split('T')[0]}
              className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-pink-400" />
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-3">Reason for Termination *</label>
            <div className="space-y-2">
              {REASONS.map(r => (
                <label key={r} className="flex items-center gap-3 p-3 rounded-xl border cursor-pointer transition-all hover:border-pink-300"
                  style={reason === r ? { borderColor: '#b828a0', background: '#fdf0fc' } : { borderColor: '#e5e7eb' }}>
                  <input type="radio" name="reason" value={r} checked={reason === r} onChange={() => setReason(r)} className="w-4 h-4 cursor-pointer" style={{ accentColor: '#b828a0' }} />
                  <span className="text-sm text-gray-700">{r}</span>
                </label>
              ))}
            </div>
            {reason === 'Other' && (
              <div className="mt-3">
                <input value={reasonOther} onChange={e => setReasonOther(e.target.value)}
                  placeholder="Please specify your reason…"
                  className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-pink-400" />
              </div>
            )}
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Additional Comments <span className="text-gray-400 font-normal">(optional)</span></label>
            <textarea value={comments} onChange={e => setComments(e.target.value)} rows={3} maxLength={500}
              placeholder="Any additional information you'd like to share…"
              className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-pink-400 resize-none" />
            <p className="text-xs text-gray-400 text-right mt-1">{comments.length}/500</p>
          </div>

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

          <label className="flex items-start gap-3 p-4 rounded-xl border cursor-pointer transition-all"
            style={confirmed ? { borderColor: '#b828a0', background: '#fdf0fc' } : { borderColor: '#e5e7eb' }}>
            <input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}
              className="w-4 h-4 mt-0.5 cursor-pointer flex-shrink-0" style={{ accentColor: '#b828a0' }} />
            <span className="text-sm text-gray-700">
              I confirm that I have read and understood that this termination request is voluntary and I understand the consequences, including the applicable notice period and any financial implications.
            </span>
          </label>
        </div>

        <div className="px-6 py-4 border-t border-gray-100 flex gap-3 justify-end">
          <button type="button" onClick={onCancel}
            className="px-5 py-2.5 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
            Cancel
          </button>
          <button type="submit"
            className="px-6 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap shadow"
            style={{ background: '#b828a0' }}>
            Submit Application
          </button>
        </div>
      </form>
    </div>
  );
}
