'use client';
import { useState } from 'react';
import { useAuth } from '../../../lib/authContext';
import EmployeeLayout from '../../../components/EmployeeLayout';
import EmployeeTerminationForm from './EmployeeTerminationForm';
import EmployeeTerminationStatus from './EmployeeTerminationStatus';
import { employeeTerminationRequests, EmployeeTerminationRequest } from '../../hr/termination/terminationData';

export default function EmployeeTerminationPage() {
  const { user } = useAuth();

  if (!user) return null;

  const [showForm, setShowForm] = useState(false);
  const [requests, setRequests] = useState<EmployeeTerminationRequest[]>(
    employeeTerminationRequests.filter(r => r.employeeId === user?.employeeId)
  );
  const [viewRequest, setViewRequest] = useState<EmployeeTerminationRequest | null>(null);

  const handleSubmit = (req: EmployeeTerminationRequest) => {
    setRequests(prev => [req, ...prev]);
    setShowForm(false);
    setViewRequest(req);
  };

  const handleWithdraw = (id: string) => {
    setRequests(prev => prev.map(r => r.id === id ? { ...r, status: 'Withdrawn' as const } : r));
    setViewRequest(null);
  };

  if (viewRequest) {
    return (
      <EmployeeLayout title="Termination Request Status">
        <EmployeeTerminationStatus
          request={requests.find(r => r.id === viewRequest.id) || viewRequest}
          onBack={() => setViewRequest(null)}
          onWithdraw={handleWithdraw}
        />
      </EmployeeLayout>
    );
  }

  if (showForm) {
    return (
      <EmployeeLayout title="Apply for Termination">
        <EmployeeTerminationForm user={user} onSubmit={handleSubmit} onCancel={() => setShowForm(false)} />
      </EmployeeLayout>
    );
  }

  return (
    <EmployeeLayout title="Termination Request">
      <div className="max-w-3xl mx-auto space-y-5">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
          <div className="flex items-start gap-5">
            <div className="w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0" style={{ background: '#fdf0fc' }}>
              <i className="ri-user-unfollow-line text-2xl" style={{ color: '#b828a0' }}></i>
            </div>
            <div className="flex-1">
              <h2 className="text-xl font-bold text-gray-800 mb-2">Termination Request</h2>
              <p className="text-gray-500 text-sm leading-relaxed mb-4">
                Submit a voluntary termination request (resignation, retirement, etc.). Your request will follow the approval chain below before being finalized.
              </p>
              <div className="flex items-center gap-2 mb-6 flex-wrap">
                {['You Submit', 'HOD Reviews', 'Manager Reviews', 'HR Final Approval'].map((step, i, arr) => (
                  <div key={step} className="flex items-center gap-2">
                    <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold" style={{ background: '#fdf0fc', color: '#b828a0' }}>
                      <span className="w-4 h-4 rounded-full bg-white flex items-center justify-center text-xs font-bold" style={{ color: '#b828a0' }}>{i + 1}</span>
                      {step}
                    </div>
                    {i < arr.length - 1 && <i className="ri-arrow-right-line text-gray-300 text-xs"></i>}
                  </div>
                ))}
              </div>
              <button onClick={() => setShowForm(true)}
                className="flex items-center gap-2 px-6 py-3 rounded-xl text-white font-semibold cursor-pointer whitespace-nowrap shadow-md"
                style={{ background: '#b828a0' }}>
                <div className="w-5 h-5 flex items-center justify-center"><i className="ri-add-line"></i></div>
                Apply for Termination
              </button>
            </div>
          </div>
        </div>

        <div className="bg-amber-50 border border-amber-200 rounded-2xl p-5 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 HOD and HR will be notified. Please ensure you have read your employment contract and understand the notice period requirements. You may withdraw your application while it is still pending review.</p>
          </div>
        </div>

        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="p-5 border-b border-gray-100 flex items-center justify-between">
            <h3 className="font-semibold text-gray-800">Your Termination Requests</h3>
            <span className="text-xs text-gray-400">{requests.length} request(s)</span>
          </div>
          {requests.length === 0 ? (
            <div className="text-center py-12 text-gray-400">
              <div className="w-12 h-12 flex items-center justify-center mx-auto mb-3">
                <i className="ri-file-list-3-line text-4xl"></i>
              </div>
              <p className="text-sm">No termination requests submitted yet.</p>
            </div>
          ) : (
            <table className="w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  {['Application ID', 'Submission Date', 'Proposed Last Day', 'Reason', 'Status', 'Actions'].map(h => (
                    <th key={h} className="text-left text-xs font-semibold text-gray-500 px-5 py-3">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {requests.map(r => (
                  <tr key={r.id} className="border-t border-gray-50 hover:bg-gray-50">
                    <td className="px-5 py-3 font-mono text-xs text-gray-500">{r.applicationId}</td>
                    <td className="px-5 py-3 text-gray-600">{r.submittedDate}</td>
                    <td className="px-5 py-3 text-gray-600">{r.proposedLastDay}</td>
                    <td className="px-5 py-3 text-gray-600 max-w-[150px] truncate">{r.reason}</td>
                    <td className="px-5 py-3">
                      <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${
                        r.status === 'Approved' ? 'bg-green-100 text-green-700' :
                        r.status === 'Rejected' ? 'bg-red-100 text-red-700' :
                        r.status === 'Withdrawn' ? 'bg-gray-100 text-gray-600' :
                        r.status === 'Pending HR Review' ? 'bg-blue-100 text-blue-700' :
                        r.status === 'Pending HOD Review' ? 'bg-purple-100 text-purple-700' :
                        'bg-yellow-100 text-yellow-700'
                      }`}>{r.status}</span>
                    </td>
                    <td className="px-5 py-3">
                      <div className="flex gap-2">
                        <button onClick={() => setViewRequest(r)}
                          className="text-xs font-medium cursor-pointer whitespace-nowrap" style={{ color: '#b828a0' }}>
                          View
                        </button>
                        {r.status === 'Approved' && (
                          <button onClick={() => {
                            const content = `UWEZO FUND\nTERMINATION APPROVAL LETTER\n\nRef: ${r.applicationId}\nEmployee: ${r.employeeName}\nDept: ${r.department}\nFinal Date: ${r.finalTerminationDate || r.proposedLastDay}\n\nApproved by HR on ${r.hrApprovedDate || 'N/A'}\n\nUwezo Fund HRMS v2.0.1`;
                            const blob = new Blob([content], { type: 'text/plain' });
                            const url = URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            a.download = `Termination-${r.applicationId}.txt`;
                            a.click();
                            URL.revokeObjectURL(url);
                          }}
                            className="text-xs font-medium text-blue-600 cursor-pointer whitespace-nowrap">
                            Download Letter
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </EmployeeLayout>
  );
}
