"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { FileText, Plus, Search, Shield, X, Check, AlertCircle, Trash2, Briefcase, Lock, Download, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { downloadContractPDF, downloadContractPDFUrdu, getCompanyName } from "@/lib/pdf";

interface Contract {
  id: string;
  type: string;
  signedDate: string;
  expiryDate: string | null;
  status: string;
  employee: { firstName: string; lastName: string; employeeId: string; designation?: string; department?: string; cnic?: string; joiningDate?: string };
}

const CONTRACT_TYPES = ["All", "Employment Contract", "NDA", "Safety Bond"] as const;

const TYPE_META: Record<string, { icon: React.ReactNode; color: string; bg: string }> = {
  "Employment Contract": { icon: <Briefcase className="h-3.5 w-3.5" />, color: "text-brand-700",  bg: "bg-brand-50 ring-brand-600/20" },
  "NDA":                 { icon: <Lock      className="h-3.5 w-3.5" />, color: "text-slate-700",  bg: "bg-slate-50 ring-slate-600/20" },
  "Safety Bond":         { icon: <Shield    className="h-3.5 w-3.5" />, color: "text-emerald-700",bg: "bg-emerald-50 ring-emerald-600/20" },
};

const STATUS_STYLE: Record<string, string> = {
  Active:     "bg-emerald-50 text-emerald-700 ring-emerald-600/20",
  Terminated: "bg-red-50 text-red-700 ring-red-600/20",
  Expired:    "bg-gray-100 text-gray-600 ring-gray-400/20",
};

export default function ContractsPage() {
  const [contracts, setContracts] = useState<Contract[]>([]);
  const [employees, setEmployees] = useState<{id:string;firstName:string;lastName:string;employeeId:string}[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [activeTab, setActiveTab] = useState<typeof CONTRACT_TYPES[number]>("All");
  const [saving, setSaving] = useState(false);
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  const toggleExpanded = (empId: string) => setExpanded(p => ({ ...p, [empId]: !p[empId] }));
  const [empSearch, setEmpSearch] = useState("");
  const [empDropOpen, setEmpDropOpen] = useState(false);
  const empDropRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const handler = (e: MouseEvent) => { if (empDropRef.current && !empDropRef.current.contains(e.target as Node)) setEmpDropOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const [formData, setFormData] = useState({
    employeeId: "",
    type: "Employment Contract",
    signedDate: new Date().toISOString().split("T")[0],
    expiryDate: "",
    status: "Active",
  });

  const fetchAll = async () => {
    setIsLoading(true);
    try {
      const [cRes, eRes] = await Promise.all([
        authFetch(`${API}/contracts`),
        authFetch(`${API}/employees?limit=1000`),  
      ]);
      const cData = cRes.ok ? await cRes.json() : [];
      const eRaw  = eRes.ok ? await eRes.json() : [];
      const eData = Array.isArray(eRaw) ? eRaw : (eRaw.employees ?? eRaw ?? []);
      if (Array.isArray(cData)) setContracts(cData);
      setEmployees(eData);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => { fetchAll(); }, []);

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await authFetch(`${API}/contracts`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });
      if (!res.ok) { alert("Failed to save contract."); return; }
      setIsSlideOverOpen(false);
      setEmpSearch("");
      setFormData({ employeeId: "", type: "Employment Contract", signedDate: new Date().toISOString().split("T")[0], expiryDate: "", status: "Active" });
      fetchAll();
    } finally { setSaving(false); }
  };

  const updateStatus = async (id: string, status: string) => {
    await authFetch(`${API}/contracts/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    fetchAll();
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this contract?")) return;
    await authFetch(`${API}/contracts/${id}`, { method: "DELETE" });
    fetchAll();
  };

  const filtered = contracts.filter(c => {
    const q = searchQuery.toLowerCase();
    const matchesSearch = `${c.employee?.firstName} ${c.employee?.lastName}`.toLowerCase().includes(q) || c.type.toLowerCase().includes(q);
    const matchesTab = activeTab === "All" || c.type === activeTab;
    return matchesSearch && matchesTab;
  });

  const counts = {
    All: contracts.length,
    "Employment Contract": contracts.filter(c => c.type === "Employment Contract").length,
    "NDA": contracts.filter(c => c.type === "NDA").length,
    "Safety Bond": contracts.filter(c => c.type === "Safety Bond").length,
  };

  const active = contracts.filter(c => c.status === "Active").length;
  const terminated = contracts.filter(c => c.status === "Terminated").length;

  const fmtDate = (d: string) => new Date(d).toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" });

  return (
    <div className="space-y-6 pb-10">

      {/* ── Header ── */}
      <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:text-3xl sm:tracking-tight">Legal Contracts</h1>
          <p className="mt-1 text-sm text-gray-500">Employment contracts, NDAs, and safety bonds.</p>
        </div>
        <button
          onClick={() => setIsSlideOverOpen(true)}
          className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-brand-700 transition-colors"
        >
          <Plus className="h-4 w-4" /> New Contract
        </button>
      </div>

      {/* ── Stat Chips ── */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {[
          { label: "Total",      value: contracts.length, color: "text-gray-900", bg: "bg-white" },
          { label: "Active",     value: active,           color: "text-emerald-700", bg: "bg-emerald-50" },
          { label: "Terminated", value: terminated,       color: "text-red-700",     bg: "bg-red-50" },
          { label: "Employees",  value: new Set(contracts.map(c => c.employee?.employeeId)).size, color: "text-brand-700", bg: "bg-brand-50" },
        ].map(s => (
          <motion.div key={s.label} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}
            className={cn("rounded-2xl border border-gray-100 shadow-sm px-5 py-4", s.bg)}
          >
            <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">{s.label}</p>
            <p className={cn("text-2xl font-extrabold mt-1", s.color)}>{s.value}</p>
          </motion.div>
        ))}
      </div>

      {/* ── Table Card ── */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.07 }}
        className="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden"
      >
        {/* Toolbar */}
        <div className="px-6 pt-5 pb-4 border-b border-gray-100 space-y-4">
          {/* Type tabs */}
          <div className="flex gap-1 flex-wrap">
            {CONTRACT_TYPES.map(t => (
              <button key={t} onClick={() => setActiveTab(t)}
                className={cn(
                  "inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",
                  activeTab === t
                    ? "bg-brand-600 text-white"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                )}
              >
                {t !== "All" && TYPE_META[t]?.icon}
                {t}
                <span className={cn("ml-1 rounded-full px-1.5 py-0.5 text-[10px] font-bold",
                  activeTab === t ? "bg-white/20 text-white" : "bg-white text-gray-500"
                )}>
                  {counts[t]}
                </span>
              </button>
            ))}
          </div>
          {/* Search */}
          <div className="relative max-w-xs">
            <Search className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text" value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search employee or type…"
              className="w-full rounded-lg border border-gray-200 py-2 pl-9 pr-3 text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
            />
          </div>
        </div>

        {isLoading ? (
          <div className="flex items-center justify-center h-48 text-sm text-gray-400 animate-pulse">Loading contracts…</div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-48 gap-3">
            <div className="h-12 w-12 rounded-full bg-gray-100 flex items-center justify-center">
              <FileText className="h-6 w-6 text-gray-300" />
            </div>
            <p className="text-sm text-gray-400">No contracts found.</p>
            <button onClick={() => setIsSlideOverOpen(true)} className="text-xs font-semibold text-brand-600 hover:underline">+ Add one</button>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {/* Group contracts by employee */}
            {Object.values(
              filtered.reduce<Record<string, { emp: Contract["employee"]; contracts: Contract[] }>>((acc, c) => {
                const key = c.employee?.employeeId ?? "unknown";
                if (!acc[key]) acc[key] = { emp: c.employee, contracts: [] };
                acc[key].contracts.push(c);
                return acc;
              }, {})
            ).map(({ emp, contracts: empContracts }) => {
              const isOpen = expanded[emp.employeeId] ?? false;
              return (
              <div key={emp.employeeId} className="border-b border-gray-50 last:border-0">
                {/* Employee accordion header */}
                <button
                  type="button"
                  onClick={() => toggleExpanded(emp.employeeId)}
                  className="w-full flex items-center gap-3 px-6 py-4 hover:bg-gray-50/60 transition-colors text-left"
                >
                  <div className="h-9 w-9 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 font-bold text-sm uppercase">
                    {emp.firstName.charAt(0)}{emp.lastName.charAt(0)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-bold text-gray-900">{emp.firstName} {emp.lastName}</p>
                    <p className="text-xs text-gray-400 font-mono">#{emp.employeeId}{emp.designation ? ` · ${emp.designation}` : ""}{emp.department ? ` · ${emp.department}` : ""}</p>
                  </div>
                  <span className="text-xs text-gray-400 mr-2">{empContracts.length} contract{empContracts.length !== 1 ? "s" : ""}</span>
                  <ChevronDown className={cn("h-4 w-4 text-gray-400 flex-shrink-0 transition-transform duration-200", isOpen && "rotate-180")} />
                </button>

                {/* Contract rows — animated dropdown */}
                <AnimatePresence initial={false}>
                  {isOpen && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: "auto", opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      transition={{ duration: 0.2 }}
                      className="overflow-hidden"
                    >
                      <div className="px-6 pb-4 ml-12 space-y-2">
                  {empContracts.map(c => {
                    const meta = TYPE_META[c.type];
                    return (
                      <div key={c.id} className="flex items-center gap-3 rounded-xl border border-gray-100 bg-gray-50/60 px-4 py-3 hover:bg-gray-50 transition-colors">
                        {/* Type badge */}
                        <span className={cn("inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset flex-shrink-0", meta?.color, meta?.bg)}>
                          {meta?.icon}{c.type}
                        </span>

                        {/* Dates */}
                        <div className="flex items-center gap-4 text-xs text-gray-500 flex-1">
                          <span><span className="text-gray-400 font-medium">Signed </span>{fmtDate(c.signedDate)}</span>
                          <span><span className="text-gray-400 font-medium">Expiry </span>{c.expiryDate ? fmtDate(c.expiryDate) : "—"}</span>
                        </div>

                        {/* Status */}
                        <span className={cn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset flex-shrink-0",
                          STATUS_STYLE[c.status] ?? STATUS_STYLE.Expired
                        )}>
                          {c.status}
                        </span>

                        {/* Actions */}
                        <div className="flex items-center gap-1.5 flex-shrink-0">
                          <button
                            onClick={async () => {
                              const companyName = await getCompanyName();
                              downloadContractPDF({ ...c, employee: { ...emp, companyName } });
                            }}
                            className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-white bg-brand-600 hover:bg-brand-700 border border-brand-600 transition-colors"
                            title="Download English hard copy"
                          >
                            <Download className="h-3.5 w-3.5" /> EN
                          </button>
                          <button
                            onClick={async () => {
                              const companyName = await getCompanyName();
                              downloadContractPDFUrdu({ ...c, employee: { ...emp, companyName } });
                            }}
                            className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-brand-700 bg-brand-50 hover:bg-brand-100 border border-brand-100 transition-colors"
                            title="Download Urdu hard copy"
                          >
                            <Download className="h-3.5 w-3.5" /> UR
                          </button>
                          {c.status === "Active" ? (
                            <button onClick={() => updateStatus(c.id, "Terminated")}
                              className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-gray-500 bg-white hover:bg-red-50 hover:text-red-600 border border-gray-200 transition-colors"
                            >
                              <AlertCircle className="h-3.5 w-3.5" /> Terminate
                            </button>
                          ) : (
                            <button onClick={() => updateStatus(c.id, "Active")}
                              className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-gray-500 bg-white hover:bg-emerald-50 hover:text-emerald-600 border border-gray-200 transition-colors"
                            >
                              <Check className="h-3.5 w-3.5" /> Activate
                            </button>
                          )}
                          <button onClick={() => handleDelete(c.id)}
                            className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </button>
                        </div>
                      </div>
                    );
                  })}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
              );
            })}
          </div>
        )}

        {filtered.length > 0 && (
          <div className="px-6 py-3 border-t border-gray-100 bg-gray-50/40">
            <p className="text-xs text-gray-400">{filtered.length} contract{filtered.length !== 1 ? "s" : ""}</p>
          </div>
        )}
      </motion.div>

      {/* ── Slide-over ── */}
      <AnimatePresence>
        {isSlideOverOpen && (
          <>
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              onClick={() => setIsSlideOverOpen(false)}
              className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm z-40"
            />
            <motion.div initial={{ x: "100%" }} animate={{ x: 0 }} exit={{ x: "100%" }}
              transition={{ type: "spring", stiffness: 300, damping: 30 }}
              className="fixed inset-y-0 right-0 z-50 w-full max-w-sm bg-white shadow-2xl flex flex-col"
            >
              <div className="flex items-center justify-between px-6 py-5 border-b border-gray-100">
                <div className="flex items-center gap-2.5">
                  <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
                    <FileText className="h-4 w-4" />
                  </div>
                  <h2 className="text-sm font-bold text-gray-900">New Contract</h2>
                </div>
                <button onClick={() => setIsSlideOverOpen(false)} className="text-gray-400 hover:text-gray-600">
                  <X className="h-5 w-5" />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto px-6 py-6">
                <form id="contract-form" onSubmit={handleCreate} className="space-y-5">

                  {/* Contract Type — visual picker */}
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Contract Type</label>
                    <div className="grid grid-cols-1 gap-2">
                      {(["Employment Contract", "NDA", "Safety Bond"] as const).map(t => (
                        <button type="button" key={t}
                          onClick={() => setFormData(f => ({ ...f, type: t }))}
                          className={cn(
                            "flex items-center gap-3 rounded-xl border-2 px-4 py-3 text-left transition-colors",
                            formData.type === t
                              ? "border-brand-600 bg-brand-50"
                              : "border-gray-100 bg-gray-50 hover:border-gray-200"
                          )}
                        >
                          <div className={cn("flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg",
                            formData.type === t ? "bg-brand-600 text-white" : "bg-white text-gray-400"
                          )}>
                            {TYPE_META[t].icon}
                          </div>
                          <div>
                            <p className={cn("text-sm font-semibold", formData.type === t ? "text-brand-700" : "text-gray-700")}>{t}</p>
                            <p className="text-xs text-gray-400">
                              {t === "Employment Contract" ? "Standard employment agreement" :
                               t === "NDA" ? "Non-disclosure agreement" : "Safety & compliance bond"}
                            </p>
                          </div>
                          {formData.type === t && <Check className="ml-auto h-4 w-4 text-brand-600 flex-shrink-0" />}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Employee — searchable combobox */}
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Employee</label>
                    <div className="relative" ref={empDropRef}>
                      <div
                        className={cn(
                          "flex items-center gap-2 w-full rounded-lg border px-3 py-2 text-sm bg-white cursor-pointer",
                          empDropOpen ? "border-brand-600 ring-2 ring-brand-600/20" : "border-gray-200"
                        )}
                        onClick={() => setEmpDropOpen(o => !o)}
                      >
                        <Search className="h-3.5 w-3.5 text-gray-400 flex-shrink-0" />
                        <input
                          type="text"
                          value={empSearch}
                          onChange={e => { setEmpSearch(e.target.value); setEmpDropOpen(true); }}
                          onClick={e => { e.stopPropagation(); setEmpDropOpen(true); }}
                          placeholder={formData.employeeId ? (employees.find(e => e.id === formData.employeeId) ? `${employees.find(e => e.id === formData.employeeId)!.firstName} ${employees.find(e => e.id === formData.employeeId)!.lastName}` : "Select employee…") : "Search employee…"}
                          className="flex-1 bg-transparent outline-none text-gray-900 placeholder:text-gray-400 text-sm"
                        />
                        {formData.employeeId && (
                          <button type="button" onClick={e => { e.stopPropagation(); setFormData(f => ({ ...f, employeeId: "" })); setEmpSearch(""); }}
                            className="text-gray-300 hover:text-gray-500"
                          ><X className="h-3.5 w-3.5" /></button>
                        )}
                      </div>
                      {empDropOpen && (
                        <div className="absolute z-10 mt-1 w-full rounded-xl border border-gray-200 bg-white shadow-lg max-h-52 overflow-y-auto">
                          {employees
                            .filter(e => {
                              const q = empSearch.toLowerCase();
                              return !q || `${e.firstName} ${e.lastName}`.toLowerCase().includes(q) || e.employeeId.toLowerCase().includes(q);
                            })
                            .map(emp => (
                              <button type="button" key={emp.id}
                                onClick={() => { setFormData(f => ({ ...f, employeeId: emp.id })); setEmpSearch(""); setEmpDropOpen(false); }}
                                className={cn(
                                  "w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-gray-50 transition-colors",
                                  formData.employeeId === emp.id && "bg-brand-50"
                                )}
                              >
                                <div className="h-7 w-7 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 text-xs font-bold uppercase">
                                  {emp.firstName.charAt(0)}{emp.lastName.charAt(0)}
                                </div>
                                <div>
                                  <p className="text-sm font-semibold text-gray-900">{emp.firstName} {emp.lastName}</p>
                                  <p className="text-xs text-gray-400 font-mono">#{emp.employeeId}</p>
                                </div>
                                {formData.employeeId === emp.id && <Check className="ml-auto h-4 w-4 text-brand-600" />}
                              </button>
                            ))}
                          {employees.filter(e => { const q = empSearch.toLowerCase(); return !q || `${e.firstName} ${e.lastName}`.toLowerCase().includes(q) || e.employeeId.toLowerCase().includes(q); }).length === 0 && (
                            <p className="px-3 py-4 text-sm text-gray-400 text-center">No employees found</p>
                          )}
                        </div>
                      )}
                    </div>
                    {/* hidden required field */}
                    <input type="text" required readOnly value={formData.employeeId} className="sr-only" tabIndex={-1} />
                  </div>

                  {/* Dates */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Signed Date</label>
                      <input type="date" value={formData.signedDate}
                        onChange={e => setFormData(f => ({ ...f, signedDate: e.target.value }))}
                        className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Expiry Date</label>
                      <input type="date" value={formData.expiryDate}
                        onChange={e => setFormData(f => ({ ...f, expiryDate: e.target.value }))}
                        className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
                        placeholder="Optional"
                      />
                    </div>
                  </div>
                </form>
              </div>

              <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
                <button type="button" onClick={() => setIsSlideOverOpen(false)}
                  className="rounded-lg px-4 py-2 text-sm font-semibold text-gray-600 hover:bg-gray-50 border border-gray-200 transition-colors"
                >
                  Cancel
                </button>
                <button type="submit" form="contract-form" disabled={saving}
                  className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors disabled:opacity-50"
                >
                  {saving && <span className="h-3.5 w-3.5 border-2 border-white/40 border-t-white rounded-full animate-spin" />}
                  {saving ? "Saving…" : "Save Contract"}
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

