"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect, useCallback, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Banknote,
  Search,
  Download,
  FileText,
  Loader2,
  X,
  ChevronDown,
  ChevronRight,
  ArrowRight,
  ArrowLeft,
  HandCoins,
  Trash2,
  Calendar,
  Users,
} from "lucide-react";
import { downloadPayrollPDF, downloadMonthlyPayrollPDF, downloadEmployeeCopyPDF } from "@/lib/pdf";
import { cn } from "@/lib/utils";

interface PayrollRecord {
  id: string;
  month: number;
  year: number;
  basicSalary: number;
  presentDays?: number;
  workingDays?: number;
  fromDate?: string;
  toDate?: string;
  overtimePay: number;
  loansAdvance?: number;
  deductions?: number; // late / short-hours
  tax?: number;        // unpaid / absent loss
  netSalary: number;
  status: string;
  employee: {
    firstName: string;
    lastName: string;
    employeeId: string;
    department: string;
    designation: string;
    contractType: string;
    joiningDate?: string;
    cnic?: string;
  };
  loanDeductions?: {
    id: string;
    amount: number;
    loan: { description: string };
  }[];
  attendanceSummary?: {
    totalWorkedHrs: number;
    totalExpectedHrs: number;
    totalOvertimeHrs: number;
    totalDeductionHrs: number;
    lateCount: number;
    earlyOutCount: number;
    penaltyDays: number;
    deductionDays: { date: string; status: string; deductionHrs: number; deductionAmount: number }[];
  };
}

function fmtMoney(n: number) {
  return n.toLocaleString("en-PK", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

interface ActiveLoan {
  id: string;
  employeeId: string;
  description: string;
  totalAmount: number;
  remainingBalance: number;
  employee: {
    id: string;
    firstName: string;
    lastName: string;
    employeeId: string;
    department: string;
  };
}

interface LoanDeductionInput {
  loanId: string;
  employeeId: string;
  amount: number;
}

interface MonthGroup {
  key: string;
  month: number;
  year: number;
  records: PayrollRecord[];
  totalBasic: number;
  totalOT: number;
  totalLoan: number;
  totalNet: number;
  employeeCount: number;
}

export default function PayrollPage() {
  const [records, setRecords] = useState<PayrollRecord[]>([]);
  const [orgSettings, setOrgSettings] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [expandedMonth, setExpandedMonth] = useState<string | null>(null);

  const [genData, setGenData] = useState({
    month: new Date().getMonth() + 1,
    year: new Date().getFullYear(),
    genMode: "monthly" as "monthly" | "custom",
    fromDate: "",
    toDate: "",
  });

  // Two-step flow
  const [genStep, setGenStep] = useState<1 | 2>(1);
  const [activeLoans, setActiveLoans] = useState<ActiveLoan[]>([]);
  const [loanDeductions, setLoanDeductions] = useState<Record<string, number>>({});
  const [loadingLoans, setLoadingLoans] = useState(false);

  const updateStatus = async (id: string, status: string) => {
    try {
      const res = await authFetch(`${API}/dash/payroll/${id}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      });
      if (!res.ok) return;
      fetchRecords();
    } catch (e) {
      console.error(e);
    }
  };

  const fetchRecords = async () => {
    try {
      setIsLoading(true);
      const res = await authFetch(`${API}/dash/payroll`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) setRecords(data);
      else setRecords([]);
    } catch {
      setRecords([]);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchRecords();
    authFetch(`${API}/dash/settings`).then(res => res.json()).then(data => setOrgSettings(data)).catch(() => {});
  }, []);

  const deletePayroll = async (id: string) => {
    if (!confirm("Delete this payroll record?")) return;
    try {
      await authFetch(`${API}/dash/payroll/${id}`, { method: "DELETE" });
      fetchRecords();
    } catch (e) {
      console.error(e);
    }
  };

  const deleteMonth = async (month: number, year: number) => {
    if (!confirm(`Delete ALL payroll records for ${getMonthName(month)} ${year}? This cannot be undone.`)) return;
    try {
      await authFetch(`${API}/dash/payroll/month/${month}/${year}`, { method: "DELETE" });
      setExpandedMonth(null);
      fetchRecords();
    } catch (e) {
      console.error(e);
    }
  };

  const openSlideOver = () => {
    setGenStep(1);
    setActiveLoans([]);
    setLoanDeductions({});
    setIsSlideOverOpen(true);
  };

  const fetchActiveLoans = useCallback(async () => {
    setLoadingLoans(true);
    try {
      const res = await authFetch(`${API}/dash/loans/active`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) {
        setActiveLoans(data);
        const defaults: Record<string, number> = {};
        data.forEach((l: ActiveLoan) => { defaults[l.id] = 0; });
        setLoanDeductions(defaults);
      }
    } catch {
      setActiveLoans([]);
    } finally {
      setLoadingLoans(false);
    }
  }, []);

  const handleNextStep = async () => {
    await fetchActiveLoans();
    setGenStep(2);
  };

  const handleGenerate = async () => {
    try {
      setIsGenerating(true);
      const loanDeds: LoanDeductionInput[] = activeLoans
        .filter((l) => (loanDeductions[l.id] ?? 0) > 0)
        .map((l) => ({
          loanId: l.id,
          employeeId: l.employee.id,
          amount: loanDeductions[l.id],
        }));

      const res = await authFetch(`${API}/dash/payroll/generate`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 
          ...genData, 
          loanDeductions: loanDeds,
          fromDate: genData.genMode === "custom" ? genData.fromDate : undefined,
          toDate: genData.genMode === "custom" ? genData.toDate : undefined,
        }),
      });

      if (!res.ok) {
        const err = await res.json();
        alert(err.message);
      } else {
        setIsSlideOverOpen(false);
        fetchRecords();
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsGenerating(false);
    }
  };

  const getMonthName = (m: number) =>
    new Date(2000, m - 1).toLocaleString("default", { month: "long" });

  // Group records by month/year
  const monthGroups: MonthGroup[] = useMemo(() => {
    const map = new Map<string, PayrollRecord[]>();
    for (const r of records) {
      const key = `${r.year}-${String(r.month).padStart(2, "0")}`;
      if (!map.has(key)) map.set(key, []);
      map.get(key)!.push(r);
    }

    return Array.from(map.entries())
      .sort((a, b) => b[0].localeCompare(a[0]))
      .map(([key, recs]) => {
        const filtered = searchQuery
          ? recs.filter((r) => {
              const q = searchQuery.toLowerCase();
              return (
                r.employee?.firstName?.toLowerCase().includes(q) ||
                r.employee?.lastName?.toLowerCase().includes(q) ||
                r.employee?.employeeId?.toLowerCase().includes(q) ||
                r.employee?.department?.toLowerCase().includes(q)
              );
            })
          : recs;

        return {
          key,
          month: recs[0].month,
          year: recs[0].year,
          records: filtered,
          totalBasic: recs.reduce((s, r) => s + r.basicSalary, 0),
          totalOT: recs.reduce((s, r) => s + r.overtimePay, 0),
          totalLoan: recs.reduce((s, r) => s + (r.loansAdvance ?? 0), 0),
          totalNet: recs.reduce((s, r) => s + r.netSalary, 0),
          employeeCount: recs.length,
        };
      })
      .filter((g) => !searchQuery || g.records.length > 0);
  }, [records, searchQuery]);

  const toggleMonth = (key: string) => {
    setExpandedMonth((prev) => (prev === key ? null : key));
  };

  return (
    <div className="space-y-6 relative">
      {/* 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:truncate sm:text-3xl sm:tracking-tight">
            Payroll Management
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            Process salaries, OT calculations, and generate pay slips.
          </p>
        </div>
        <button
          onClick={openSlideOver}
          className="inline-flex items-center justify-center rounded-lg border border-transparent bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors"
        >
          <Banknote className="mr-2 h-4 w-4" />
          Generate Monthly Payroll
        </button>
      </div>

      {/* Search bar */}
      <div className="rounded-2xl bg-white shadow-sm border border-[#E2E8F0]">
        <div className="p-5 border-b border-gray-200 bg-gray-50/50">
          <div className="relative max-w-md w-full">
            <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
              <Search className="h-4 w-4 text-gray-400" />
            </div>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="block w-full rounded-lg border-0 py-2.5 pl-10 pr-3 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-brand-600 sm:text-sm sm:leading-6"
              placeholder="Search by employee name, ID, department..."
            />
          </div>
        </div>

        {isLoading ? (
          <div className="p-12 text-center text-sm text-gray-500">Loading payroll data...</div>
        ) : monthGroups.length === 0 ? (
          <div className="flex flex-col items-center justify-center p-16 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-brand-50 mb-4">
              <Banknote className="h-8 w-8 text-brand-600" />
            </div>
            <h3 className="text-lg font-medium text-gray-900">No payroll processed</h3>
            <p className="mt-1 text-sm text-gray-500 max-w-sm">
              Generate your first payroll cycle to see records here.
            </p>
          </div>
        ) : (
          <div className="divide-y divide-gray-200">
            {monthGroups.map((group) => {
              const isOpen = expandedMonth === group.key;
              return (
                <div key={group.key}>
                  {/* Month header row — clickable */}
                  <button
                    onClick={() => toggleMonth(group.key)}
                    className="w-full flex items-center justify-between px-6 py-4 hover:bg-gray-50 transition-colors text-left group"
                  >
                    <div className="flex items-center gap-4">
                      <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-brand-100 text-brand-700 group-hover:bg-brand-200 transition-colors">
                        <Calendar className="h-5 w-5" />
                      </div>
                      <div>
                        <div className="text-base font-semibold text-gray-900">
                          {getMonthName(group.month)} {group.year}
                          {group.records[0]?.fromDate && group.records[0]?.toDate && (
                            <span className="ml-2 text-[10px] font-normal text-gray-400 border border-gray-200 px-1.5 py-0.5 rounded uppercase tracking-tighter">
                              {new Date(group.records[0].fromDate).toLocaleDateString("en-PK", { day: "2-digit", month: "short" })} - {new Date(group.records[0].toDate).toLocaleDateString("en-PK", { day: "2-digit", month: "short" })}
                            </span>
                          )}
                        </div>
                        <div className="flex items-center gap-3 mt-0.5 text-xs text-gray-500">
                          <span className="flex items-center gap-1">
                            <Users className="h-3 w-3" />
                            {group.employeeCount} employees
                          </span>
                          <span>Basic: Rs. {fmtMoney(group.totalBasic)}</span>
                          <span className="text-green-600">OT: Rs. {fmtMoney(group.totalOT)}</span>
                          {group.totalLoan > 0 && (
                            <span className="text-red-600">Loan: Rs. {fmtMoney(group.totalLoan)}</span>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="text-right mr-2">
                        <div className="text-lg font-bold text-brand-600">
                          Rs. {fmtMoney(group.totalNet)}
                        </div>
                        <div className="text-[10px] text-gray-400 font-medium uppercase tracking-wider">
                          Total Net
                        </div>
                      </div>
                      <motion.div
                        animate={{ rotate: isOpen ? 90 : 0 }}
                        transition={{ duration: 0.2 }}
                      >
                        <ChevronRight className="h-5 w-5 text-gray-400" />
                      </motion.div>
                    </div>
                  </button>

                  {/* Expanded — individual employee payrolls */}
                  <AnimatePresence initial={false}>
                    {isOpen && (
                      <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: "auto", opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.25 }}
                        className="overflow-hidden"
                      >
                        <div className="bg-gray-50/60 border-t border-gray-100">
                          {/* Action bar */}
                          <div className="flex items-center justify-between px-6 py-3 border-b border-gray-200/80">
                            <span className="text-xs font-semibold uppercase tracking-wider text-gray-400">
                              Employee Payrolls — {getMonthName(group.month)} {group.year}
                            </span>
                            <div className="flex items-center gap-2">
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  downloadMonthlyPayrollPDF(group.records, orgSettings?.name);
                                }}
                                className="inline-flex items-center gap-1.5 rounded-lg bg-white px-3 py-1.5 text-xs font-medium text-gray-700 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 transition-colors"
                              >
                                <Download className="h-3.5 w-3.5" />
                                Download PDF
                              </button>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation();
                                  deleteMonth(group.month, group.year);
                                }}
                                className="inline-flex items-center gap-1.5 rounded-lg bg-white px-3 py-1.5 text-xs font-medium text-red-600 shadow-sm ring-1 ring-inset ring-red-200 hover:bg-red-50 transition-colors"
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                                Delete Month
                              </button>
                            </div>
                          </div>

                          {/* Table */}
                          <div className="overflow-x-auto">
                            <table className="min-w-full divide-y divide-gray-200">
                              <thead className="bg-gray-100/80">
                                <tr>
                                  <th className="py-3 pl-6 pr-3 text-left text-xs font-semibold text-gray-600">Employee</th>
                                  <th className="px-3 py-3 text-center text-xs font-semibold text-gray-600">Days</th>
                                  <th className="px-3 py-3 text-left text-xs font-semibold text-gray-600">Base Salary</th>
                                  <th className="px-3 py-3 text-left text-xs font-semibold text-gray-600">OT Pay</th>
                                  <th className="px-3 py-3 text-left text-xs font-semibold text-gray-600">Loan Ded.</th>
                                  <th className="px-3 py-3 text-left text-xs font-semibold text-gray-600">Net Salary</th>
                                  <th className="px-3 py-3 text-left text-xs font-semibold text-gray-600">Status</th>
                                  <th className="py-3 px-6 text-center text-xs font-semibold text-gray-600">Actions</th>
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-gray-100 bg-white">
                                {group.records.map((record) => (
                                  <tr key={record.id} className="hover:bg-gray-50/70 transition-colors">
                                    <td className="whitespace-nowrap py-3 pl-6 pr-3 text-sm">
                                      <div className="flex items-center">
                                        <div className="h-9 w-9 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 text-xs font-bold uppercase ring-2 ring-white">
                                          {record.employee?.firstName?.charAt(0)}
                                          {record.employee?.lastName?.charAt(0)}
                                        </div>
                                        <div className="ml-3">
                                          <div className="font-medium text-gray-900 text-sm">
                                            {record.employee?.firstName} {record.employee?.lastName}
                                          </div>
                                          <div className="text-gray-400 text-[11px] font-mono">
                                            #{record.employee?.employeeId} · {record.employee?.department}
                                          </div>
                                        </div>
                                      </div>
                                    </td>
                                    <td className="whitespace-nowrap px-3 py-3 text-sm text-center">
                                      <span className={cn(
                                        "inline-flex items-center justify-center rounded-full px-2 py-0.5 text-xs font-bold",
                                        (record.presentDays ?? 0) >= (record.workingDays ?? 26)
                                          ? "bg-green-50 text-green-700"
                                          : "bg-amber-50 text-amber-700"
                                      )}>
                                        {record.presentDays ?? 0}/{record.workingDays ?? 26}
                                      </span>
                                    </td>
                                    <td className="whitespace-nowrap px-3 py-3 text-sm text-gray-900">
                                      Rs. {fmtMoney(record.basicSalary)}
                                    </td>
                                    <td className="whitespace-nowrap px-3 py-3 text-sm text-green-600 font-medium">
                                      + Rs. {fmtMoney(record.overtimePay)}
                                    </td>
                                    <td className="whitespace-nowrap px-3 py-3 text-sm text-red-600 font-medium">
                                      {(record.loansAdvance ?? 0) > 0
                                        ? `- Rs. ${fmtMoney(record.loansAdvance ?? 0)}`
                                        : "—"}
                                    </td>
                                    <td className="whitespace-nowrap px-3 py-3 text-sm font-bold text-brand-600">
                                      Rs. {fmtMoney(record.netSalary)}
                                    </td>
                                    <td className="whitespace-nowrap px-3 py-3 text-sm">
                                      <select
                                        value={record.status}
                                        onChange={(e) => updateStatus(record.id, e.target.value)}
                                        className={cn(
                                          "h-7 rounded-full border-0 bg-white px-2.5 text-[11px] font-medium shadow-sm ring-1 ring-inset focus:outline-none focus:ring-2",
                                          record.status === "PAID"
                                            ? "bg-green-50 text-green-700 ring-green-600/20"
                                            : record.status === "PROCESSED"
                                              ? "bg-blue-50 text-blue-700 ring-blue-700/10"
                                              : record.status === "PENDING_APPROVAL"
                                                ? "bg-amber-50 text-amber-700 ring-amber-600/20"
                                                : "bg-gray-50 text-gray-700 ring-gray-400/40"
                                        )}
                                      >
                                        <option value="DRAFT">Draft</option>
                                        <option value="PENDING_APPROVAL">Pending</option>
                                        <option value="PROCESSED">Processed</option>
                                        <option value="PAID">Paid</option>
                                      </select>
                                    </td>
                                    <td className="whitespace-nowrap py-3 px-6 text-center text-sm">
                                      <div className="flex items-center justify-center gap-1.5">
                                        <button
                                          onClick={async () => {
                                            const empId = record.employee?.employeeId;
                                            let attendanceSummary = undefined;
                                            try {
                                              const rangeParams = record.fromDate && record.toDate
                                                ? `&startDate=${record.fromDate}&endDate=${record.toDate}`
                                                : `&month=${record.month}&year=${record.year}`;
                                                
                                              const res = await authFetch(`${API}/dash/attendance?employeeId=${empId}${rangeParams}`);
                                              const rows = res.ok ? await res.json() : [];
                                              const workedStatuses = new Set(["PRESENT", "LATE", "HALF_DAY", "EARLY_OUT"]);
                                              const byDate = new Map<string, any>();
                                              for (const a of rows) {
                                                const key = a.date.substring(0, 10);
                                                const ex = byDate.get(key);
                                                if (!ex || (a.checkOut != null && ex.checkOut == null) || new Date(a.updatedAt) > new Date(ex.updatedAt)) {
                                                  byDate.set(key, a);
                                                }
                                              }
                                              const active = Array.from(byDate.values()).filter((a: any) => workedStatuses.has(a.status));
                                              
                                              const holidayCalendar = (() => {
                                                try {
                                                  const p = typeof orgSettings?.holidayCalendar === "string" ? JSON.parse(orgSettings.holidayCalendar) : orgSettings?.holidayCalendar;
                                                  return Array.isArray(p) ? p : [];
                                                } catch { return []; }
                                              })();
                                              const holidaysInRange = [];
                                              if (record.fromDate && record.toDate) {
                                                const rS = new Date(record.fromDate); rS.setHours(0,0,0,0);
                                                const rE = new Date(record.toDate); rE.setHours(23,59,59,999);
                                                for (const h of holidayCalendar) {
                                                  const hS = new Date(h.startDate);
                                                  const hE = new Date(h.endDate);
                                                  if (hS <= rE && hE >= rS) holidaysInRange.push(h);
                                                }
                                              }

                                              const lateDays = active.filter((a: any) => a.status === "LATE");
                                              const deductionDays = active
                                                .filter((a: any) => (a.deductionHrs ?? 0) > 0)
                                                .sort((a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime())
                                                .map((a: any) => ({ date: a.date, status: a.status, deductionHrs: a.deductionHrs ?? 0, deductionAmount: a.deductionAmount ?? 0 }));

                                              const stdHrs = parseFloat(orgSettings?.workingHours ?? "9");
                                              attendanceSummary = {
                                                totalWorkedHrs: active.reduce((s: number, a: any) => s + (a.totalWorkedHrs ?? 0), 0),
                                                totalExpectedHrs: active.length * stdHrs,
                                                totalOvertimeHrs: active.reduce((s: number, a: any) => s + (a.overtimeHrs ?? 0), 0),
                                                totalDeductionHrs: active.reduce((s: number, a: any) => s + (a.deductionHrs ?? 0), 0),
                                                lateCount: lateDays.length,
                                                earlyOutCount: active.filter((a: any) => a.status === "EARLY_OUT").length,
                                                penaltyDays: lateDays.filter((a: any) => (a.deductionHrs ?? 0) > 0).length,
                                                deductionDays,
                                                holidays: holidaysInRange,
                                              };
                                            } catch (e) { console.error("Attendance fetch error:", e); }
                                            await downloadPayrollPDF({ 
                                              ...record, 
                                              attendanceSummary, 
                                              periodLabel: `${getMonthName(record.month)} ${record.year}`,
                                              workingHours: parseFloat(orgSettings?.workingHours ?? "9"),
                                              salaryDivisor: parseFloat(orgSettings?.salaryDivisor ?? "30"),
                                              companyName: orgSettings?.name,
                                            }, true);
                                          }}
                                          className="text-brand-600 hover:text-brand-900 bg-brand-50 p-1.5 rounded-lg"
                                          title="Download payslip"
                                        >
                                          <Download className="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                          onClick={() => {
                                            downloadEmployeeCopyPDF({ 
                                              ...record, 
                                              salaryDivisor: parseFloat(orgSettings?.salaryDivisor ?? "30"),
                                              companyName: orgSettings?.name,
                                            });
                                          }}
                                          className="text-amber-600 hover:text-amber-900 bg-amber-50 p-1.5 rounded-lg"
                                          title="Download employee copy (simplified)"
                                        >
                                          <FileText className="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                          onClick={() => deletePayroll(record.id)}
                                          className="text-red-500 hover:text-red-700 bg-red-50 p-1.5 rounded-lg"
                                          title="Delete payroll"
                                        >
                                          <Trash2 className="h-3.5 w-3.5" />
                                        </button>
                                      </div>
                                    </td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Slide-over for Generate Payroll — Two-step flow */}
      <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 transition-opacity"
            />
            <motion.div
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", bounce: 0, duration: 0.4 }}
              className="fixed inset-y-0 right-0 z-50 w-full max-w-lg bg-white text-gray-900 shadow-2xl flex flex-col border-l border-gray-200"
            >
              <div className="flex items-center justify-between px-6 py-5 border-b border-gray-100 bg-white/50 backdrop-blur-md">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-brand-50 border border-brand-100">
                    <Banknote className="h-5 w-5 text-brand-600" />
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-gray-900">Run Payroll Cycle</h2>
                    <p className="text-xs text-gray-500 font-medium mt-0.5">
                      Step {genStep} of 2 — {genStep === 1 ? "Select period" : "Review loan deductions"}
                    </p>
                  </div>
                </div>
                <button
                  onClick={() => setIsSlideOverOpen(false)}
                  className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto px-6 py-6 custom-scrollbar bg-gray-50/30">
                {genStep === 1 ? (
                  <div className="space-y-6">
                    <div className="space-y-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-900/5">
                    <div className="space-y-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-900/5">
                      <div className="flex p-1 bg-gray-100 rounded-lg mb-2">
                        <button
                          onClick={() => setGenData({ ...genData, genMode: "monthly" })}
                          className={cn(
                            "flex-1 py-1.5 text-xs font-semibold rounded-md transition-colors",
                            genData.genMode === "monthly" ? "bg-white text-brand-600 shadow-sm" : "text-gray-500"
                          )}
                        >Standard Monthly</button>
                        <button
                          onClick={() => setGenData({ ...genData, genMode: "custom" })}
                          className={cn(
                            "flex-1 py-1.5 text-xs font-semibold rounded-md transition-colors",
                            genData.genMode === "custom" ? "bg-white text-brand-600 shadow-sm" : "text-gray-500"
                          )}
                        >Custom Date Range</button>
                      </div>

                      {genData.genMode === "monthly" ? (
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Target Month</label>
                            <select
                              required
                              value={genData.month}
                              onChange={(e) => setGenData({ ...genData, month: Number(e.target.value) })}
                              className="block w-full rounded-lg border-0 py-2.5 pl-3 pr-8 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm sm:leading-6 transition-colors shadow-sm appearance-none"
                            >
                              {[...Array(12)].map((_, i) => (
                                <option key={i + 1} value={i + 1}>{getMonthName(i + 1)}</option>
                              ))}
                            </select>
                          </div>
                          <div>
                            <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Target Year</label>
                            <input
                              required
                              type="number"
                              value={genData.year}
                              onChange={(e) => setGenData({ ...genData, year: Number(e.target.value) })}
                              className="block w-full rounded-lg border-0 py-2.5 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-inset focus:ring-brand-600 sm:text-sm sm:leading-6 transition-colors shadow-sm"
                            />
                          </div>
                        </div>
                      ) : (
                        <div className="space-y-4">
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">From Date</label>
                              <input
                                type="date"
                                required
                                value={genData.fromDate}
                                onChange={(e) => setGenData({ ...genData, fromDate: e.target.value })}
                                className="block w-full rounded-lg border-0 py-2.5 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm shadow-sm"
                              />
                            </div>
                            <div>
                              <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">To Date</label>
                              <input
                                type="date"
                                required
                                value={genData.toDate}
                                onChange={(e) => setGenData({ ...genData, toDate: e.target.value })}
                                className="block w-full rounded-lg border-0 py-2.5 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm shadow-sm"
                              />
                            </div>
                          </div>
                          <div className="grid grid-cols-2 gap-4">
                            <div>
                              <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Label as Month</label>
                              <select
                                required
                                value={genData.month}
                                onChange={(e) => setGenData({ ...genData, month: Number(e.target.value) })}
                                className="block w-full rounded-lg border-0 py-2.5 pl-3 pr-8 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm shadow-sm appearance-none"
                              >
                                {[...Array(12)].map((_, i) => (
                                  <option key={i + 1} value={i + 1}>{getMonthName(i + 1)}</option>
                                ))}
                              </select>
                            </div>
                            <div>
                              <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Label as Year</label>
                              <input
                                required
                                type="number"
                                value={genData.year}
                                onChange={(e) => setGenData({ ...genData, year: Number(e.target.value) })}
                                className="block w-full rounded-lg border-0 py-2.5 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm shadow-sm"
                              />
                            </div>
                          </div>
                        </div>
                      )}

                      <div className="rounded-lg bg-brand-50 p-4 border border-brand-100">
                        <h4 className="text-xs font-bold text-brand-700 uppercase mb-2 flex items-center">
                          <FileText className="h-3 w-3 mr-1" />
                          Processing Details
                        </h4>
                        <p className="text-xs text-brand-600 leading-relaxed">
                          {genData.genMode === "monthly" 
                            ? "The system will scan attendance logs for every employee from the 1st to the last day of the month."
                            : `The system will scan attendance logs specifically from ${genData.fromDate || '...'} to ${genData.toDate || '...'}.`
                          } OT will be calculated at 2x daily rate. In the next step you can add loan deductions.
                        </p>
                      </div>
                    </div>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-4">
                    <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-900/5">
                      <div className="flex items-center gap-2 mb-4">
                        <HandCoins className="h-5 w-5 text-brand-600" />
                        <h3 className="text-sm font-semibold text-gray-900">Active Loan Deductions</h3>
                      </div>
                      <p className="text-xs text-gray-500 mb-4">
                        Enter the amount to deduct from each employee&apos;s salary this month. Leave blank or 0 to skip.
                      </p>

                      {loadingLoans ? (
                        <div className="py-8 text-center text-sm text-gray-400 flex items-center justify-center gap-2">
                          <Loader2 className="h-4 w-4 animate-spin" />
                          Loading active loans...
                        </div>
                      ) : activeLoans.length === 0 ? (
                        <div className="py-6 text-center text-sm text-gray-400">
                          No active loans found. You can proceed to generate payroll without deductions.
                        </div>
                      ) : (
                        <div className="space-y-3 max-h-[400px] overflow-y-auto">
                          {activeLoans.map((loan) => (
                            <div
                              key={loan.id}
                              className="rounded-lg border border-gray-200 p-3 hover:border-brand-200 transition-colors"
                            >
                              <div className="flex items-center justify-between mb-2">
                                <div>
                                  <span className="text-sm font-medium text-gray-900">
                                    {loan.employee.firstName} {loan.employee.lastName}
                                  </span>
                                  <span className="text-xs text-gray-400 ml-2 font-mono">
                                    #{loan.employee.employeeId}
                                  </span>
                                </div>
                                <span className="text-xs font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
                                  ACTIVE
                                </span>
                              </div>
                              <div className="text-xs text-gray-500 mb-2">{loan.description}</div>
                              <div className="grid grid-cols-3 gap-2 text-xs mb-2">
                                <div>
                                  <span className="text-gray-400">Total:</span>
                                  <span className="ml-1 font-medium text-gray-700">Rs. {loan.totalAmount.toLocaleString()}</span>
                                </div>
                                <div>
                                  <span className="text-gray-400">Remaining:</span>
                                  <span className="ml-1 font-bold text-brand-600">Rs. {loan.remainingBalance.toLocaleString()}</span>
                                </div>
                                <div>
                                  <span className="text-gray-400">Paid:</span>
                                  <span className="ml-1 font-medium text-red-600">
                                    Rs. {(loan.totalAmount - loan.remainingBalance).toLocaleString()}
                                  </span>
                                </div>
                              </div>
                              <div>
                                <label className="block text-xs font-semibold text-gray-500 mb-1">
                                  Deduct This Month (Rs.)
                                </label>
                                <input
                                  type="number"
                                  min="0"
                                  max={loan.remainingBalance}
                                  step="1"
                                  value={loanDeductions[loan.id] || ""}
                                  onChange={(e) =>
                                    setLoanDeductions({ ...loanDeductions, [loan.id]: Number(e.target.value) || 0 })
                                  }
                                  placeholder="0"
                                  className="block w-full rounded-lg border-0 py-2 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm transition-colors shadow-sm"
                                />
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>

              <div className="border-t border-gray-100 px-6 py-4 bg-white flex items-center justify-between">
                {genStep === 1 ? (
                  <>
                    <button
                      type="button"
                      onClick={() => setIsSlideOverOpen(false)}
                      className="rounded-lg bg-white px-4 py-2 text-sm font-semibold text-gray-700 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 transition-colors"
                    >
                      Cancel
                    </button>
                    <button
                      type="button"
                      onClick={handleNextStep}
                      className="inline-flex items-center rounded-lg bg-brand-600 px-6 py-2 text-sm font-semibold text-white shadow-sm hover:bg-brand-500 transition-colors"
                    >
                      Next
                      <ArrowRight className="ml-2 h-4 w-4" />
                    </button>
                  </>
                ) : (
                  <>
                    <button
                      type="button"
                      onClick={() => setGenStep(1)}
                      className="inline-flex items-center rounded-lg bg-white px-4 py-2 text-sm font-semibold text-gray-700 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 transition-colors"
                    >
                      <ArrowLeft className="mr-2 h-4 w-4" />
                      Back
                    </button>
                    <button
                      type="button"
                      onClick={handleGenerate}
                      disabled={isGenerating}
                      className="inline-flex items-center rounded-lg bg-brand-600 px-6 py-2 text-sm font-semibold text-white shadow-sm hover:bg-brand-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {isGenerating ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Processing...
                        </>
                      ) : (
                        "Generate Payroll"
                      )}
                    </button>
                  </>
                )}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}



