"use client";

import { API, authFetch } from "@/lib/api";
import { useEffect, useMemo, useState } from "react";
import { motion } from "framer-motion";
import { Download } from "lucide-react";
import { downloadQuiteEmployeesPDF } from "@/lib/pdf";

type Employee = {
  id: string;
  employeeId: string;
  firstName: string;
  lastName: string;
  cnic: string;
  department: string;
  designation: string;
  joiningDate: string;
  basicSalary: number;
};

type Contract = {
  id: string;
  type: string;
  employee: { employeeId: string };
  status: string;
  expiryDate: string | null;
};

export default function LeavedEmployeesPage() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [contracts, setContracts] = useState<Contract[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDownloading, setIsDownloading] = useState(false);

  useEffect(() => {
    const run = async () => {
      try {
        setIsLoading(true);
        const [empRes, contractRes] = await Promise.all([
          authFetch(`${API}/dash/employees`),
          authFetch(`${API}/dash/contracts`),
        ]);

        const empRaw = empRes.ok ? await empRes.json() : [];
        const empData = Array.isArray(empRaw) ? empRaw : (empRaw.employees ?? []);
        const contractData = contractRes.ok ? await contractRes.json() : [];

        setEmployees(Array.isArray(empData) ? empData : []);
        setContracts(Array.isArray(contractData) ? contractData : []);
      } catch {
        setEmployees([]);
        setContracts([]);
      } finally {
        setIsLoading(false);
      }
    };

    run();
  }, []);

  const leavedEmployees = useMemo(() => {
    const terminated = contracts.filter(
      (c) => c?.status === "Terminated" && c?.employee?.employeeId,
    );

    // latest terminated contract per employeeId
    const latestByEmpId = new Map<string, Contract>();
    for (const c of terminated) {
      const empId = String(c.employee.employeeId ?? "");
      const expiry = c.expiryDate ? new Date(c.expiryDate).getTime() : 0;
      const prev = latestByEmpId.get(empId);
      const prevExpiry = prev?.expiryDate ? new Date(prev.expiryDate).getTime() : 0;
      if (!prev || expiry > prevExpiry) latestByEmpId.set(empId, c);
    }

    const byEmployeeId = new Map(employees.map((e) => [e.employeeId, e]));

    const list = [];
    for (const [empId, c] of latestByEmpId.entries()) {
      const emp = byEmployeeId.get(empId);
      if (!emp) continue;
      list.push({
        employeeId: emp.employeeId,
        firstName: emp.firstName,
        lastName: emp.lastName,
        department: emp.department,
        designation: emp.designation,
        joiningDate: emp.joiningDate,
        leavingDate: c.expiryDate ? new Date(c.expiryDate).toISOString().slice(0, 10) : emp.joiningDate,
        separationType: c.type === "Resigned" ? "Resigned" : "Terminated",
        cnic: emp.cnic,
        basicSalary: emp.basicSalary,
      });
    }

    list.sort((a, b) => (a.leavingDate < b.leavingDate ? 1 : -1));
    return list;
  }, [employees, contracts]);

  const handleDownload = async () => {
    if (!leavedEmployees.length) return;
    if (!confirm(`Download Quite Employees PDF for ${leavedEmployees.length} employee(s)?`))
      return;

    setIsDownloading(true);
    try {
      downloadQuiteEmployeesPDF(leavedEmployees);
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <div className="space-y-6 relative">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
            Resigned Employees
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            Employees who have resigned or been terminated.
          </p>
        </div>

        <div className="flex items-center gap-3">
          <button
            onClick={handleDownload}
            disabled={isLoading || isDownloading || leavedEmployees.length === 0}
            className="inline-flex items-center justify-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <Download className="h-4 w-4" />
            {isDownloading ? "Preparing..." : "Download PDF"}
          </button>
        </div>
      </div>

      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.08 }}
        className="rounded-2xl bg-white shadow-sm border border-[#E2E8F0] overflow-hidden"
      >
        <div className="p-6 border-b border-gray-200 bg-gray-50/50">
          <p className="text-sm text-gray-600">
            {isLoading ? "Loading..." : `${leavedEmployees.length} employee(s) found.`}
          </p>
        </div>

        {isLoading ? (
          <div className="p-12 text-center text-sm text-gray-500">Loading leaved employees...</div>
        ) : leavedEmployees.length === 0 ? (
          <div className="p-12 text-center text-sm text-gray-500">No terminated employees found.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-300">
              <thead className="bg-gray-50">
                <tr>
                  <th className="py-3.5 pl-6 pr-3 text-left text-sm font-semibold text-gray-900">
                    Name
                  </th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                    Code
                  </th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                    Department / Designation
                  </th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                    Status
                  </th>
                  <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                    Leaving Date
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 bg-white">
                {leavedEmployees.map((e) => (
                  <tr key={e.employeeId} className="hover:bg-gray-50/60 transition-colors">
                    <td className="whitespace-nowrap py-4 pl-6 pr-3 text-sm font-medium text-gray-900">
                      {e.firstName} {e.lastName}
                    </td>
                    <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-600 font-mono">
                      {e.employeeId}
                    </td>
                    <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-600">
                      {e.department} / {e.designation}
                    </td>
                    <td className="whitespace-nowrap px-3 py-4 text-sm">
                      <span className="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset bg-gray-100 text-gray-600 ring-gray-400/30">
                        {e.separationType}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-600">
                      {e.leavingDate}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </motion.div>
    </div>
  );
}




