"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Landmark, Plus, Search, Layers, RefreshCw, CheckCircle, TrendingUp, Download } from "lucide-react";
import { downloadSocialSecurityPDF, downloadEobiPessiReportPDF } from "@/lib/pdf";
import { cn } from "@/lib/utils";

interface SocialSecurityRecord {
  id: string;
  month: number;
  year: number;
  employee: { firstName: string; lastName: string; employeeId: string };
  eobiEmployer: number | null;
  eobiEmployee: number | null;
  pessiEmployer: number | null;
  pessiEmployee: number | null;
}

export default function SocialSecurityPage() {
  const [records, setRecords] = useState<SocialSecurityRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterMonth, setFilterMonth] = useState<number | "all">(new Date().getMonth() + 1);
  const [filterYear, setFilterYear] = useState<number | "all">(new Date().getFullYear());

  const [autoData, setAutoData] = useState({ month: new Date().getMonth() + 1, year: new Date().getFullYear() });

  const PAGE_SIZE = 10;
  const [currentPage, setCurrentPage] = useState(1);

  const fetchRecords = async () => {
    try {
      setIsLoading(true);
      const res = await authFetch(`${API}/social-security`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) setRecords(data);
    } catch (e) {
      console.error(e);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchRecords();
  }, []);

  const [isAutomating, setIsAutomating] = useState(false);

  const handleAutomate = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsAutomating(true);
    try {
      const res = await authFetch(`${API}/social-security/automate`, {
         method: "POST",
         headers: { "Content-Type": "application/json" },
         body: JSON.stringify(autoData),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.message ?? "Failed");
      setIsSlideOverOpen(false);
      await fetchRecords();
      alert(`Done! Created ${data.created} record${data.created !== 1 ? "s" : ""} for ${autoData.month}/${autoData.year}.`);
    } catch (err: unknown) {
      alert("Error: " + (err instanceof Error ? err.message : "Something went wrong"));
    } finally {
      setIsAutomating(false);
    }
  };

  const filteredRecords = records.filter((r) => {
    const q = searchQuery.toLowerCase();
    const employeeName = `${r.employee?.firstName ?? ''} ${r.employee?.lastName ?? ''}`.toLowerCase();
    return (
      employeeName.includes(q) &&
      (filterMonth === 'all' || r.month === filterMonth) &&
      (filterYear === 'all' || r.year === filterYear)
    );
  });

  const totalPages = Math.max(1, Math.ceil(filteredRecords.length / PAGE_SIZE));
  const pagedRecords = filteredRecords.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE);

  const totalMonthlyCost = filteredRecords.reduce((sum, r) => {
    const eobiTotal = (r.eobiEmployer ?? 0) + (r.eobiEmployee ?? 0);
    const pessiTotal = (r.pessiEmployer ?? 0) + (r.pessiEmployee ?? 0);
    return sum + eobiTotal + pessiTotal;
  }, 0);

  const employerTotal = filteredRecords.reduce((sum, r) => {
    return sum + (r.eobiEmployer ?? 0) + (r.pessiEmployer ?? 0);
  }, 0);

  const employeeTotal = filteredRecords.reduce((sum, r) => {
    return sum + (r.eobiEmployee ?? 0) + (r.pessiEmployee ?? 0);
  }, 0);

  const employerShare =
    totalMonthlyCost > 0 ? Math.round((employerTotal / totalMonthlyCost) * 100) : 0;
  void employerShare;

  const MONTHS = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

  const fmt = (n: number) => `Rs. ${n.toLocaleString("en-PK", { minimumFractionDigits: 2 })}`;

  return (
    <div className="space-y-6 pb-10">

      {/* ── Page 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">
            EOBI &amp; PESSI
          </h1>
          <p className="mt-1 text-sm text-gray-500">Social security contributions and legal reporting.</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => downloadEobiPessiReportPDF(filteredRecords)}
            disabled={filteredRecords.length === 0}
            className="inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 transition-colors disabled:opacity-50"
          >
            <Download className="h-4 w-4" /> Export PDF
          </button>
          <button
            onClick={() => setIsSlideOverOpen(true)}
            className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors"
          >
            <RefreshCw className="h-4 w-4" /> Automate Monthly
          </button>
        </div>
      </div>

      {/* ── Stat Cards ── */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
        {[
          {
            label: "Total Monthly Cost",
            value: fmt(totalMonthlyCost),
            sub: "EOBI + PESSI combined",
            icon: <TrendingUp className="h-5 w-5" />,
            color: "bg-brand-50 text-brand-600",
          },
          {
            label: "Active Members",
            value: `${filteredRecords.length} Workers`,
            sub: "With contributions in period",
            icon: <CheckCircle className="h-5 w-5" />,
            color: "bg-emerald-50 text-emerald-600",
          },
          {
            label: "Employer Share",
            value: fmt(employerTotal),
            sub: `Worker share: ${fmt(employeeTotal)}`,
            icon: <Layers className="h-5 w-5" />,
            color: "bg-slate-50 text-slate-600",
          },
        ].map((s) => (
          <motion.div
            key={s.label}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="rounded-2xl bg-white border border-gray-100 shadow-sm p-6 flex items-start justify-between gap-4"
          >
            <div>
              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">{s.label}</p>
              <p className="mt-1.5 text-xl font-extrabold text-gray-900 leading-tight">{s.value}</p>
              <p className="mt-1 text-xs text-gray-400">{s.sub}</p>
            </div>
            <div className={cn("flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl", s.color)}>
              {s.icon}
            </div>
          </motion.div>
        ))}
      </div>

      {/* ── Table Card ── */}
      <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-gray-100 overflow-hidden"
      >
        {/* Toolbar */}
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 px-6 py-4 border-b border-gray-100 bg-gray-50/40">
          <div className="relative max-w-xs w-full">
            <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); setCurrentPage(1); }}
              placeholder="Search employee…"
              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 className="flex items-center gap-2 flex-wrap">
            <span className="text-xs font-semibold text-gray-400 uppercase">Period:</span>
            <select
              value={filterMonth}
              onChange={e => setFilterMonth(e.target.value === "all" ? "all" : Number(e.target.value))}
              className="rounded-lg border border-gray-200 py-1.5 px-3 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
            >
              <option value="all">All Months</option>
              {Array.from({ length: 12 }, (_, i) => (
                <option key={i + 1} value={i + 1}>{new Date(2000, i).toLocaleString("default", { month: "long" })}</option>
              ))}
            </select>
            <select
              value={filterYear}
              onChange={e => setFilterYear(e.target.value === "all" ? "all" : Number(e.target.value))}
              className="rounded-lg border border-gray-200 py-1.5 px-3 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
            >
              <option value="all">All Years</option>
              {[2026, 2025, 2024].map(y => <option key={y} value={y}>{y}</option>)}
            </select>
            {(filterMonth !== "all" || filterYear !== "all") && (
              <button
                onClick={() => { setFilterMonth("all"); setFilterYear("all"); setCurrentPage(1); }}
                className="text-xs font-semibold text-brand-600 hover:underline"
              >
                Clear
              </button>
            )}
          </div>
        </div>

        {isLoading ? (
          <div className="flex items-center justify-center h-48 text-sm text-gray-400 animate-pulse">
            Loading records…
          </div>
        ) : filteredRecords.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">
              <Landmark className="h-6 w-6 text-gray-300" />
            </div>
            <p className="text-sm text-gray-400">No records found for the selected period.</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="min-w-full">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-100">
                  <th className="py-3 pl-6 pr-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">Employee</th>
                  <th className="px-3 py-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">Period</th>
                  <th className="px-3 py-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">EOBI Employer</th>
                  <th className="px-3 py-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">EOBI Worker</th>
                  <th className="px-3 py-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">PESSI Employer</th>
                  <th className="px-3 py-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">PESSI Worker</th>
                  <th className="px-3 py-3 text-left text-xs font-bold text-gray-400 uppercase tracking-wider">Total</th>
                  <th className="px-6 py-3 text-right text-xs font-bold text-gray-400 uppercase tracking-wider">PDF</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {pagedRecords.map((r) => {
                  const rowTotal = (r.eobiEmployer ?? 0) + (r.eobiEmployee ?? 0) + (r.pessiEmployer ?? 0) + (r.pessiEmployee ?? 0);
                  return (
                    <tr key={r.id} className="hover:bg-gray-50/60 transition-colors">
                      <td className="whitespace-nowrap py-4 pl-6 pr-3">
                        <p className="text-sm font-semibold text-gray-900">{r.employee?.firstName} {r.employee?.lastName}</p>
                        <p className="text-xs text-gray-400 font-mono mt-0.5">#{r.employee?.employeeId}</p>
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-600">
                        {MONTHS[r.month]} {r.year}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900 font-medium">
                        Rs. {(r.eobiEmployer ?? 0).toLocaleString("en-PK")}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-600">
                        Rs. {(r.eobiEmployee ?? 0).toLocaleString("en-PK")}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900 font-medium">
                        Rs. {(r.pessiEmployer ?? 0).toLocaleString("en-PK")}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-600">
                        Rs. {(r.pessiEmployee ?? 0).toLocaleString("en-PK")}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm font-bold text-brand-600">
                        Rs. {rowTotal.toLocaleString("en-PK")}
                      </td>
                      <td className="whitespace-nowrap px-6 py-4 text-right">
                        <button
                          onClick={() => downloadSocialSecurityPDF(r)}
                          className="inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-brand-600 bg-brand-50 hover:bg-brand-100 transition-colors"
                          title="Download PDF"
                        >
                          <Download className="h-3.5 w-3.5" /> PDF
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {filteredRecords.length > 0 && (
          <div className="px-6 py-3 border-t border-gray-100 bg-gray-50/40 flex items-center justify-between gap-4 flex-wrap">
            <p className="text-xs text-gray-400">
              {filteredRecords.length > PAGE_SIZE
                ? `Showing ${(currentPage - 1) * PAGE_SIZE + 1}–${Math.min(currentPage * PAGE_SIZE, filteredRecords.length)} of ${filteredRecords.length} · Total: `
                : `${filteredRecords.length} record${filteredRecords.length !== 1 ? "s" : ""} · Total: `}
              <span className="font-semibold text-brand-600">{fmt(totalMonthlyCost)}</span>
            </p>
            {filteredRecords.length > PAGE_SIZE && (
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="rounded-lg px-3 py-1.5 text-xs font-semibold text-gray-600 border border-gray-200 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                >← Prev</button>
                {Array.from({ length: totalPages }, (_, i) => i + 1)
                  .filter(p => p === 1 || p === totalPages || Math.abs(p - currentPage) <= 1)
                  .reduce<(number | "...")[]>((acc, p, i, arr) => {
                    if (i > 0 && (p as number) - (arr[i - 1] as number) > 1) acc.push("...");
                    acc.push(p);
                    return acc;
                  }, [])
                  .map((p, i) =>
                    p === "..." ? (
                      <span key={`ellipsis-${i}`} className="px-2 text-xs text-gray-400">…</span>
                    ) : (
                      <button key={p}
                        onClick={() => setCurrentPage(p as number)}
                        className={cn(
                          "rounded-lg w-8 h-8 text-xs font-semibold transition-colors",
                          currentPage === p ? "bg-brand-600 text-white" : "border border-gray-200 text-gray-600 hover:bg-gray-100"
                        )}
                      >{p}</button>
                    )
                  )}
                <button
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                  className="rounded-lg px-3 py-1.5 text-xs font-semibold text-gray-600 border border-gray-200 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                >Next →</button>
              </div>
            )}
          </div>
        )}
      </motion.div>

      {/* ── Automate 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">
                    <RefreshCw className="h-4 w-4" />
                  </div>
                  <h2 className="text-sm font-bold text-gray-900">Automated Batch Filing</h2>
                </div>
                <button onClick={() => setIsSlideOverOpen(false)} className="text-gray-400 hover:text-gray-600 text-xs font-medium">✕</button>
              </div>

              <div className="flex-1 overflow-y-auto px-6 py-6">
                <form id="auto-form" onSubmit={handleAutomate} className="space-y-5">
                  <div className="rounded-xl bg-gray-50 border border-gray-200 p-4 text-sm text-gray-600 leading-relaxed">
                    Generates social security records for <span className="font-semibold text-gray-900">every active employee</span> based on Pakistan minimum wage laws for the selected period.
                  </div>
                  <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">Month</label>
                      <input
                        type="number" min="1" max="12"
                        value={autoData.month}
                        onChange={e => setAutoData({ ...autoData, month: Number(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">Year</label>
                      <input
                        type="number"
                        value={autoData.year}
                        onChange={e => setAutoData({ ...autoData, year: Number(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>
                </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="auto-form" disabled={isAutomating}
                  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"
                >
                  {isAutomating && <RefreshCw className="h-4 w-4 animate-spin" />}
                  {isAutomating ? "Processing…" : "Run Filing"}
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

