"use client";

import { useState, useEffect, useMemo } from "react";
import { Download, Loader2, CalendarDays, Users, Clock, Wallet, Briefcase, Filter, X, TrendingUp, CheckCircle, AlertCircle, BarChart2 } from "lucide-react";
import { API, authFetch } from "@/lib/api";
import {
  downloadEmployeeReportPDF,
  downloadAttendanceReportPDF,
  downloadPayrollSummaryReportPDF,
  downloadLeaveReportPDF,
} from "@/lib/pdf";
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell,
} from "recharts";

// ─── Types ────────────────────────────────────────────────────────────────────
interface Employee {
  firstName: string; lastName: string; department: string;
  designation: string; contractType: string; joiningDate: string; basicSalary: number;
}
interface Attendance {
  date: string; status: string; overtimeHrs: number;
  employee: { firstName: string; lastName: string; employeeId: string; department: string };
}
interface Payroll {
  month: number; year: number; basicSalary: number; netSalary: number; status: string;
  employee: { firstName: string; lastName: string; employeeId: string; department: string; designation: string };
}
interface Leave {
  type: string; status: string; startDate: string; endDate: string;
  employee: { firstName: string; lastName: string; department: string };
}

const MONTHS     = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const SHORT_MON  = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const YEARS      = [2024, 2025, 2026];
const CHART_COLORS = ["#0ea5e9","#10b981","#f59e0b","#ef4444","#06b6d4","#f97316","#ec4899","#84cc16"];

function KpiCard({ label, value, sub, icon: Icon, accent }: {
  label: string; value: string | number; sub?: string;
  icon: React.ElementType; accent?: string;
}) {
  return (
    <div className="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 flex items-start gap-4 relative overflow-hidden">
      <div className={`flex h-11 w-11 items-center justify-center rounded-xl flex-shrink-0 ${accent ?? "bg-brand-50 text-brand-600"}`}>
        <Icon className="h-5 w-5" />
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-2xl font-extrabold text-gray-900 leading-none tracking-tight">{value}</p>
        <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider mt-1.5">{label}</p>
        {sub && <p className="text-xs text-gray-400 mt-0.5">{sub}</p>}
      </div>
      <div className="absolute bottom-0 right-0 w-16 h-16 rounded-tl-3xl opacity-[0.04] bg-current" />
    </div>
  );
}

function SectionCard({ title, description, onDownload, downloading, isLoading, children, accent }: {
  title: string; description: string;
  onDownload?: () => void; downloading?: boolean; isLoading: boolean;
  children: React.ReactNode; accent?: string;
}) {
  return (
    <div className="rounded-2xl bg-white border border-gray-100 shadow-sm overflow-hidden">
      <div className={`flex items-center justify-between px-6 py-5 border-b border-gray-100 ${accent ?? ""}`}>
        <div className="flex items-center gap-3">
          <div className="w-1 h-8 rounded-full bg-brand-500 flex-shrink-0" />
          <div>
            <h2 className="text-base font-bold text-gray-900">{title}</h2>
            <p className="text-xs text-gray-400 mt-0.5">{description}</p>
          </div>
        </div>
        {onDownload && (
          <button
            onClick={onDownload}
            disabled={downloading || isLoading}
            className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-xs font-semibold text-white hover:bg-brand-700 disabled:opacity-50 transition-colors shadow-sm"
          >
            {downloading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Download className="h-3.5 w-3.5" />}
            Export PDF
          </button>
        )}
      </div>
      <div className="p-6">{children}</div>
    </div>
  );
}

function StatRow({ label, value, color, max }: { label: string; value: number; color: string; max: number }) {
  const pct = max > 0 ? (value / max) * 100 : 0;
  return (
    <div className="flex items-center gap-3">
      <span className="w-24 text-xs text-gray-500 flex-shrink-0 text-right">{label}</span>
      <div className="flex-1 bg-gray-100 rounded-full h-2">
        <div className={`h-2 rounded-full ${color}`} style={{ width: `${pct}%` }} />
      </div>
      <span className="w-8 text-xs font-semibold text-gray-700 text-right">{value}</span>
    </div>
  );
}

function MonthYearPicker({ month, year, onChange }: {
  month: number; year: number; onChange: (m: number, y: number) => void;
}) {
  return (
    <div className="flex items-center gap-1.5">
      <CalendarDays className="h-3.5 w-3.5 text-gray-400" />
      <select value={month} onChange={e => onChange(Number(e.target.value), year)}
        className="rounded border-0 py-1 pl-2 pr-6 text-xs text-gray-700 ring-1 ring-inset ring-gray-300 focus:ring-brand-500 bg-white appearance-none">
        {SHORT_MON.map((m, i) => <option key={m} value={i + 1}>{m}</option>)}
      </select>
      <select value={year} onChange={e => onChange(month, Number(e.target.value))}
        className="rounded border-0 py-1 pl-2 pr-5 text-xs text-gray-700 ring-1 ring-inset ring-gray-300 focus:ring-brand-500 bg-white appearance-none">
        {YEARS.map(y => <option key={y} value={y}>{y}</option>)}
      </select>
    </div>
  );
}

// ─── Preset helpers ───────────────────────────────────────────────────────────
function getPresetRange(preset: string): { from: string; to: string } {
  const now  = new Date();
  const pad  = (n: number) => String(n).padStart(2, "0");
  const iso  = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;

  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  if (preset === "today") {
    return { from: iso(today), to: iso(today) };
  }
  if (preset === "week") {
    const start = new Date(today); start.setDate(today.getDate() - today.getDay());
    const end   = new Date(start); end.setDate(start.getDate() + 6);
    return { from: iso(start), to: iso(end) };
  }
  if (preset === "month") {
    const start = new Date(now.getFullYear(), now.getMonth(), 1);
    const end   = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    return { from: iso(start), to: iso(end) };
  }
  if (preset === "last_month") {
    const start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    const end   = new Date(now.getFullYear(), now.getMonth(), 0);
    return { from: iso(start), to: iso(end) };
  }
  if (preset === "quarter") {
    const q = Math.floor(now.getMonth() / 3);
    const start = new Date(now.getFullYear(), q * 3, 1);
    const end   = new Date(now.getFullYear(), q * 3 + 3, 0);
    return { from: iso(start), to: iso(end) };
  }
  if (preset === "year") {
    return { from: `${now.getFullYear()}-01-01`, to: `${now.getFullYear()}-12-31` };
  }
  return { from: "", to: "" };
}

const PRESETS = [
  { id: "today",      label: "Today" },
  { id: "week",       label: "This Week" },
  { id: "month",      label: "This Month" },
  { id: "last_month", label: "Last Month" },
  { id: "quarter",    label: "This Quarter" },
  { id: "year",       label: "This Year" },
];

// ─── Page ─────────────────────────────────────────────────────────────────────
export default function ReportsPage() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [attendance, setAttendance] = useState<Attendance[]>([]);
  const [payroll,    setPayroll]    = useState<Payroll[]>([]);
  const [leaves,     setLeaves]     = useState<Leave[]>([]);
  const [isLoading,  setIsLoading]  = useState(true);

  // ── Global date filter ────────────────────────────────────────────────────
  const defaultRange = getPresetRange("month");
  const [activePreset, setActivePreset] = useState("month");
  const [fromDate, setFromDate] = useState(defaultRange.from);
  const [toDate,   setToDate]   = useState(defaultRange.to);

  const applyPreset = (id: string) => {
    setActivePreset(id);
    const r = getPresetRange(id);
    setFromDate(r.from);
    setToDate(r.to);
  };

  const clearFilter = () => {
    setActivePreset("");
    setFromDate("");
    setToDate("");
  };

  const inRange = (dateStr: string) => {
    if (!fromDate && !toDate) return true;
    const d = new Date(dateStr);
    const f = fromDate ? new Date(fromDate) : null;
    const t = toDate   ? new Date(toDate)   : null;
    if (f) f.setHours(0,0,0,0);
    if (t) t.setHours(23,59,59,999);
    if (f && d < f) return false;
    if (t && d > t) return false;
    return true;
  };

  const [attMonth, setAttMonth] = useState(new Date().getMonth() + 1);
  const [attYear,  setAttYear]  = useState(new Date().getFullYear());
  const [payMonth, setPayMonth] = useState(new Date().getMonth() + 1);
  const [payYear,  setPayYear]  = useState(new Date().getFullYear());
  const [dl, setDl] = useState<string | null>(null);

  useEffect(() => {
    Promise.all([
      authFetch(`${API}/dash/employees?limit=1000`).then(r => r.json()),
      authFetch(`${API}/dash/attendance`).then(r => r.json()),
      authFetch(`${API}/dash/payroll`).then(r => r.json()),
      authFetch(`${API}/dash/leaves`).then(r => r.json()),
    ]).then(([e, a, p, l]) => {
      if (e && e.employees && Array.isArray(e.employees)) setEmployees(e.employees);
      else if (Array.isArray(e)) setEmployees(e);
      
      if (Array.isArray(a)) setAttendance(a);
      if (Array.isArray(p)) setPayroll(p);
      if (Array.isArray(l)) setLeaves(l);
    }).catch(() => {}).finally(() => setIsLoading(false));
  }, []);

  // Sync section pickers when global filter changes
  useEffect(() => {
    if (fromDate) {
      const d = new Date(fromDate);
      setAttMonth(d.getMonth() + 1); setAttYear(d.getFullYear());
      setPayMonth(d.getMonth() + 1); setPayYear(d.getFullYear());
    }
  }, [fromDate]);

  const run = async (id: string, fn: () => void) => {
    setDl(id); await new Promise(r => setTimeout(r, 80)); fn(); setDl(null);
  };

  // ── Filtered ──────────────────────────────────────────────────────────────
  // Attendance: global range filter
  const filtAtt = useMemo(() =>
    attendance.filter(a => inRange(a.date)),
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [attendance, fromDate, toDate]);

  // Also support per-section month picker (falls back to global filter if set)
  const filtAttSection = useMemo(() => {
    if (fromDate || toDate) return filtAtt;
    return attendance.filter(a => {
      const d = new Date(a.date);
      return d.getFullYear() === attYear && d.getMonth() + 1 === attMonth;
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [attendance, filtAtt, attMonth, attYear, fromDate, toDate]);

  const filtPay = useMemo(() => {
    if (fromDate || toDate) {
      return payroll.filter(p => {
        const d = new Date(p.year, p.month - 1, 1);
        return inRange(d.toISOString());
      });
    }
    return payroll.filter(p => p.month === payMonth && p.year === payYear);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [payroll, payMonth, payYear, fromDate, toDate]);

  const filtLeaves = useMemo(() =>
    leaves.filter(l => !fromDate && !toDate ? true : inRange(l.startDate)),
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [leaves, fromDate, toDate]);

  const filterLabel = fromDate || toDate
    ? `${fromDate || "—"} → ${toDate || "—"}`
    : "All time";

  // ── Employee charts ───────────────────────────────────────────────────────
  const deptData = Object.entries(
    employees.reduce((acc, e) => { acc[e.department] = (acc[e.department] || 0) + 1; return acc; }, {} as Record<string, number>)
  ).map(([name, value]) => ({ name, value }));

  const contractData = [
    { name: "Permanent", value: employees.filter(e => e.contractType === "PERMANENT").length },
    { name: "Contract",  value: employees.filter(e => e.contractType === "CONTRACT").length },
    { name: "Probation", value: employees.filter(e => e.contractType === "PROBATION").length },
    { name: "Intern",    value: employees.filter(e => e.contractType === "INTERN").length },
  ].filter(d => d.value > 0);

  // ── Attendance charts ─────────────────────────────────────────────────────
  const attSummary = [
    { name: "Present", value: filtAttSection.filter(a => a.status === "PRESENT").length, fill: "#10b981" },
    { name: "Late",    value: filtAttSection.filter(a => a.status === "LATE").length,    fill: "#f59e0b" },
    { name: "Absent",  value: filtAttSection.filter(a => a.status === "ABSENT").length,  fill: "#ef4444" },
  ];

  // Daily breakdown for the period
  const dailyAtt = Object.entries(
    filtAttSection.reduce((acc, a) => {
      const d = new Date(a.date);
      const key = `${String(d.getMonth()+1).padStart(2,"0")}/${String(d.getDate()).padStart(2,"0")}`;
      if (!acc[key]) acc[key] = { P: 0, L: 0, A: 0 };
      if (a.status === "PRESENT") acc[key].P++;
      else if (a.status === "LATE") acc[key].L++;
      else acc[key].A++;
      return acc;
    }, {} as Record<string, { P: number; L: number; A: number }>)
  )
    .sort((a, b) => a[0].localeCompare(b[0]))
    .map(([day, v]) => ({ day, ...v }));

  // ── Payroll charts ────────────────────────────────────────────────────────
  const totalNet   = filtPay.reduce((s, p) => s + (p.netSalary   || 0), 0);
  const totalGross = filtPay.reduce((s, p) => s + (p.basicSalary || 0), 0);
  const payByDept  = Object.entries(
    filtPay.reduce((acc, p) => {
      const d = p.employee?.department || "Unknown";
      acc[d] = (acc[d] || 0) + (p.netSalary || 0);
      return acc;
    }, {} as Record<string, number>)
  ).map(([name, value]) => ({ name, value: Math.round(value) }));

  // Monthly payroll trend (last 6 months)
  const payTrend = Array.from({ length: 6 }, (_, i) => {
    const d = new Date(); d.setMonth(d.getMonth() - (5 - i));
    const m = d.getMonth() + 1; const y = d.getFullYear();
    const net = payroll.filter(p => p.month === m && p.year === y)
      .reduce((s, p) => s + (p.netSalary || 0), 0);
    return { month: SHORT_MON[m - 1], net: Math.round(net) };
  });

  // ── Leave charts ──────────────────────────────────────────────────────────
  const leaveByType = Object.entries(
    filtLeaves.reduce((acc, l) => { acc[l.type] = (acc[l.type] || 0) + 1; return acc; }, {} as Record<string, number>)
  ).map(([name, value]) => ({ name, value }));

  const leaveByStatus = [
    { name: "Approved", value: filtLeaves.filter(l => l.status === "APPROVED").length, fill: "#10b981" },
    { name: "Pending",  value: filtLeaves.filter(l => l.status === "PENDING").length,  fill: "#f59e0b" },
    { name: "Rejected", value: filtLeaves.filter(l => l.status === "REJECTED").length, fill: "#ef4444" },
  ];

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center h-72 gap-3 text-gray-400">
        <Loader2 className="h-8 w-8 animate-spin text-brand-500" />
        <p className="text-sm font-medium">Loading report data…</p>
      </div>
    );
  }

  return (
    <div className="space-y-8">

      {/* 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">Reports &amp; Analytics</h1>
          <p className="mt-1 text-sm text-gray-500">Live workforce data — export any section as a branded PDF.</p>
        </div>
        {(fromDate || toDate) && (
          <div className="inline-flex items-center gap-2 rounded-xl bg-brand-50 border border-brand-200 px-3.5 py-2">
            <CalendarDays className="h-3.5 w-3.5 text-brand-500" />
            <span className="text-xs font-bold text-brand-700">{filterLabel}</span>
            <button onClick={clearFilter} className="text-brand-400 hover:text-brand-600 ml-1">
              <X className="h-3.5 w-3.5" />
            </button>
          </div>
        )}
      </div>

      {/* ── Global Date Filter Bar ─────────────────────────────────────── */}
      <div className="rounded-2xl bg-white border border-gray-200 shadow-sm p-4">
        <div className="flex flex-col sm:flex-row sm:items-center gap-4">
          {/* Preset buttons */}
          <div className="flex items-center gap-1.5 flex-wrap">
            <Filter className="h-3.5 w-3.5 text-gray-400 flex-shrink-0 mr-1" />
            {PRESETS.map(p => (
              <button
                key={p.id}
                onClick={() => applyPreset(p.id)}
                className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors ${
                  activePreset === p.id
                    ? "bg-brand-600 text-white shadow-sm"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                {p.label}
              </button>
            ))}
          </div>

          {/* Divider */}
          <div className="hidden sm:block h-6 w-px bg-gray-200 flex-shrink-0" />

          {/* Custom date range */}
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-xs text-gray-400 flex-shrink-0">Custom:</span>
            <div className="flex items-center gap-1.5">
              <input
                type="date"
                value={fromDate}
                onChange={e => { setFromDate(e.target.value); setActivePreset(""); }}
                className="rounded-lg border-0 py-1.5 px-2 text-xs text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-brand-500 bg-white"
              />
              <span className="text-xs text-gray-400">to</span>
              <input
                type="date"
                value={toDate}
                onChange={e => { setToDate(e.target.value); setActivePreset(""); }}
                className="rounded-lg border-0 py-1.5 px-2 text-xs text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-brand-500 bg-white"
              />
            </div>
            {(fromDate || toDate) && (
              <button onClick={clearFilter} className="text-xs text-gray-400 hover:text-red-500 transition-colors flex items-center gap-1">
                <X className="h-3 w-3" /> Clear
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Top KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard
          label="Total Employees"
          value={employees.length}
          sub={`${contractData.find(c=>c.name==="Permanent")?.value ?? 0} permanent`}
          icon={Users}
          accent="bg-brand-50 text-brand-600"
        />
        <KpiCard
          label="Attendance Logs"
          value={filtAttSection.length}
          sub={`${attSummary[0].value} present · ${attSummary[1].value} late`}
          icon={Clock}
          accent="bg-emerald-50 text-emerald-600"
        />
        <KpiCard
          label="Net Payroll"
          value={`Rs. ${Math.round(totalNet).toLocaleString("en-PK",{maximumFractionDigits:0})}`}
          sub={`${filtPay.length} employees`}
          icon={Wallet}
          accent="bg-sky-50 text-sky-600"
        />
        <KpiCard
          label="Leave Requests"
          value={filtLeaves.length}
          sub={`${filtLeaves.filter(l=>l.status==="PENDING").length} pending approval`}
          icon={Briefcase}
          accent="bg-amber-50 text-amber-600"
        />
      </div>

      {/* ── Section 1: Employees ─────────────────────────────────────────── */}
      <SectionCard
        title="Employee Report"
        description="Headcount by department, contract breakdown and full staff directory."
        onDownload={() => run("emp", () => downloadEmployeeReportPDF(employees))}
        downloading={dl === "emp"}
        isLoading={isLoading}
      >
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-8">
          {[
            { label: "Total Staff",  value: employees.length,                                                                color: "text-gray-900",   bg: "bg-gray-50" },
            { label: "Permanent",    value: employees.filter(e=>e.contractType==="PERMANENT").length,                        color: "text-brand-700",  bg: "bg-brand-50" },
            { label: "Departments",  value: new Set(employees.map(e=>e.department)).size,                                    color: "text-emerald-700", bg: "bg-emerald-50" },
            { label: "Avg. Salary",  value: `Rs. ${employees.length ? Math.round(employees.reduce((s,e)=>s+e.basicSalary,0)/employees.length).toLocaleString("en-PK") : 0}`, color: "text-sky-700", bg: "bg-sky-50" },
          ].map(s => (
            <div key={s.label} className={`rounded-xl border border-gray-100 p-4 text-center ${s.bg}`}>
              <p className={`text-2xl font-extrabold ${s.color}`}>{s.value}</p>
              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mt-1.5">{s.label}</p>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-4">By Department</p>
            {deptData.length === 0 ? <p className="text-xs text-gray-400">No data</p> : (
              <div className="space-y-2.5">
                {deptData.sort((a,b)=>b.value-a.value).map(d => (
                  <StatRow key={d.name} label={d.name} value={d.value} max={employees.length} color="bg-brand-500" />
                ))}
              </div>
            )}
          </div>
          <div>
            <p className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-4">By Contract Type</p>
            {contractData.length === 0 ? <p className="text-xs text-gray-400">No data</p> : (
              <div className="space-y-3 pt-1">
                {contractData.sort((a,b) => b.value - a.value).map((d, i) => {
                  const pct = employees.length > 0 ? Math.round((d.value / employees.length) * 100) : 0;
                  return (
                    <div key={d.name}>
                      <div className="flex justify-between items-center mb-1">
                        <div className="flex items-center gap-2">
                          <span className="inline-block w-2.5 h-2.5 rounded-sm flex-shrink-0" style={{ background: CHART_COLORS[i % CHART_COLORS.length] }} />
                          <span className="text-xs text-gray-600">{d.name}</span>
                        </div>
                        <span className="text-xs font-semibold text-gray-700">{d.value} <span className="font-normal text-gray-400">({pct}%)</span></span>
                      </div>
                      <div className="h-2.5 w-full bg-gray-100 rounded-full overflow-hidden">
                        <div className="h-full rounded-full transition-all" style={{ width: `${pct}%`, background: CHART_COLORS[i % CHART_COLORS.length] }} />
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </SectionCard>

      {/* ── Section 2: Attendance ────────────────────────────────────────── */}
      <SectionCard
        title="Attendance Report"
        description="Daily punch records with present, late and absent breakdown."
        onDownload={() => run("att", () => downloadAttendanceReportPDF(filtAtt, `${MONTHS[attMonth-1]} ${attYear}`))}
        downloading={dl === "att"}
        isLoading={isLoading}
      >
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
          <div className="grid grid-cols-4 gap-3 flex-1">
            {[
              { label: "Total Logs", value: filtAtt.length,        color: "text-gray-900",   bg: "bg-gray-50" },
              { label: "Present",    value: attSummary[0].value,   color: "text-emerald-700", bg: "bg-emerald-50" },
              { label: "Late",       value: attSummary[1].value,   color: "text-amber-700",  bg: "bg-amber-50" },
              { label: "Absent",     value: attSummary[2].value,   color: "text-red-700",    bg: "bg-red-50" },
            ].map(s => (
              <div key={s.label} className={`rounded-xl border border-gray-100 p-3 text-center ${s.bg}`}>
                <p className={`text-2xl font-extrabold ${s.color}`}>{s.value}</p>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mt-1">{s.label}</p>
              </div>
            ))}
          </div>
          <MonthYearPicker month={attMonth} year={attYear} onChange={(m,y)=>{setAttMonth(m);setAttYear(y);}} />
        </div>

        {dailyAtt.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 gap-2 text-gray-300">
            <BarChart2 className="h-10 w-10" />
            <p className="text-xs text-gray-400 font-medium">No attendance data for this period.</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            <div>
              <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">Daily Breakdown</p>
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={dailyAtt.slice(-14)} barSize={8} barGap={2}>
                  <XAxis dataKey="day" tick={{ fontSize: 10, fill: "#9ca3af" }} axisLine={false} tickLine={false} />
                  <YAxis hide />
                  <Tooltip
                    contentStyle={{ fontSize: 11, borderRadius: 8, border: "1px solid #e5e7eb", boxShadow: "0 4px 6px -1px rgba(0,0,0,.08)" }}
                    cursor={{ fill: "#f3f4f6" }}
                  />
                  <Bar dataKey="P" name="Present" fill="#10b981" radius={[3,3,0,0]} />
                  <Bar dataKey="L" name="Late"    fill="#f59e0b" radius={[3,3,0,0]} />
                  <Bar dataKey="A" name="Absent"  fill="#ef4444" radius={[3,3,0,0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
            <div>
              <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">Status Distribution</p>
              <div className="space-y-3 mt-2">
                {attSummary.map(s => {
                  const pct = filtAttSection.length > 0 ? Math.round((s.value / filtAttSection.length) * 100) : 0;
                  return (
                    <div key={s.name}>
                      <div className="flex justify-between items-center mb-1">
                        <div className="flex items-center gap-2">
                          <span className="inline-block w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ background: s.fill }} />
                          <span className="text-xs font-medium text-gray-600">{s.name}</span>
                        </div>
                        <span className="text-xs font-bold text-gray-700">{s.value} <span className="font-normal text-gray-400">({pct}%)</span></span>
                      </div>
                      <div className="h-2 w-full bg-gray-100 rounded-full overflow-hidden">
                        <div className="h-full rounded-full transition-all duration-500" style={{ width: `${pct}%`, background: s.fill }} />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}
      </SectionCard>

      {/* ── Section 3: Payroll ───────────────────────────────────────────── */}
      <SectionCard
        title="Payroll Report"
        description="Monthly salary register, net payable totals and 6-month trend."
        onDownload={() => run("pay", () => downloadPayrollSummaryReportPDF(filtPay, `${MONTHS[payMonth-1]} ${payYear}`))}
        downloading={dl === "pay"}
        isLoading={isLoading}
      >
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
          <div className="grid grid-cols-4 gap-3 flex-1">
            {[
              { label: "Employees",   value: filtPay.length,                                                              color: "text-gray-900",   bg: "bg-gray-50" },
              { label: "Gross Total", value: `Rs. ${Math.round(totalGross).toLocaleString("en-PK")}`,                       color: "text-brand-700",  bg: "bg-brand-50" },
              { label: "Net Payable", value: `Rs. ${Math.round(totalNet).toLocaleString("en-PK")}`,                         color: "text-sky-700", bg: "bg-sky-50" },
              { label: "Paid",        value: `${filtPay.filter(p=>p.status==="PAID").length} / ${filtPay.length}`,           color: "text-emerald-700",bg: "bg-emerald-50" },
            ].map(s => (
              <div key={s.label} className={`rounded-xl border border-gray-100 p-3 text-center ${s.bg}`}>
                <p className={`text-xl font-extrabold ${s.color}`}>{s.value}</p>
                <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mt-1">{s.label}</p>
              </div>
            ))}
          </div>
          <MonthYearPicker month={payMonth} year={payYear} onChange={(m,y)=>{setPayMonth(m);setPayYear(y);}} />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">6-Month Net Payroll Trend</p>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={payTrend} barSize={22}>
                <XAxis dataKey="month" tick={{ fontSize: 10, fill: "#9ca3af" }} axisLine={false} tickLine={false} />
                <YAxis hide />
                <Tooltip
                  formatter={(v: any) => [`Rs. ${Number(v||0).toLocaleString("en-PK")}`, "Net Pay"]}
                  contentStyle={{ fontSize: 11, borderRadius: 8, border: "1px solid #e5e7eb", boxShadow: "0 4px 6px -1px rgba(0,0,0,.08)" }}
                  cursor={{ fill: "#f3f4f6" }}
                />
                <Bar dataKey="net" name="Net Pay" radius={[4,4,0,0]}>
                  {payTrend.map((entry, index) => (
                    <Cell key={index} fill={index === payTrend.length - 1 ? "#0284c7" : "#bae6fd"} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">Net Pay by Department — {MONTHS[payMonth-1]}</p>
            {payByDept.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-8 gap-2 text-gray-300">
                <BarChart2 className="h-8 w-8" />
                <p className="text-xs text-gray-400">No payroll data for this period.</p>
              </div>
            ) : (
              <div className="space-y-3 mt-1">
                {payByDept.sort((a,b)=>b.value-a.value).map((d,i) => (
                  <div key={d.name} className="flex items-center gap-3">
                    <span className="w-28 text-xs text-gray-500 flex-shrink-0 text-right truncate">{d.name}</span>
                    <div className="flex-1 bg-gray-100 rounded-full h-2.5 overflow-hidden">
                      <div className="h-full rounded-full transition-all duration-500"
                        style={{ width: `${payByDept[0].value > 0 ? (d.value/payByDept[0].value)*100 : 0}%`, backgroundColor: CHART_COLORS[i % CHART_COLORS.length] }}
                      />
                    </div>
                    <span className="w-24 text-xs font-semibold text-gray-700 text-right">Rs. {(d.value/1000).toFixed(0)}k</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </SectionCard>

      {/* ── Section 4: Leaves ────────────────────────────────────────────── */}
      <SectionCard
        title="Leave Report"
        description="All leave requests with type, approval status and department breakdown."
        onDownload={() => run("lv", () => downloadLeaveReportPDF(filtLeaves))}
        downloading={dl === "lv"}
        isLoading={isLoading}
      >
        <div className="grid grid-cols-4 gap-3 mb-8">
          {[
            { label: "Total",    value: filtLeaves.length,       color: "text-gray-900",    bg: "bg-gray-50" },
            { label: "Approved", value: leaveByStatus[0].value,  color: "text-emerald-700", bg: "bg-emerald-50" },
            { label: "Pending",  value: leaveByStatus[1].value,  color: "text-amber-700",   bg: "bg-amber-50" },
            { label: "Rejected", value: leaveByStatus[2].value,  color: "text-red-700",     bg: "bg-red-50" },
          ].map(s => (
            <div key={s.label} className={`rounded-xl border border-gray-100 p-3 text-center ${s.bg}`}>
              <p className={`text-2xl font-extrabold ${s.color}`}>{s.value}</p>
              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mt-1">{s.label}</p>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">By Leave Type</p>
            {leaveByType.length === 0 ? <p className="text-xs text-gray-400">No data</p> : (
              <div className="space-y-2.5">
                {leaveByType.sort((a,b)=>b.value-a.value).map((l,i) => (
                  <StatRow key={l.name} label={l.name} value={l.value} max={leaves.length} color={["bg-brand-500","bg-emerald-500","bg-amber-500","bg-red-500"][i % 4]} />
                ))}
              </div>
            )}
          </div>
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">Approval Status</p>
            {filtLeaves.length === 0 ? <p className="text-xs text-gray-400">No data</p> : (
              <div className="space-y-3 pt-1">
                {leaveByStatus.map(s => {
                  const pct = filtLeaves.length > 0 ? Math.round((s.value / filtLeaves.length) * 100) : 0;
                  return (
                    <div key={s.name}>
                      <div className="flex justify-between items-center mb-1">
                        <div className="flex items-center gap-2">
                          <span className="inline-block w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ background: s.fill }} />
                          <span className="text-xs text-gray-600">{s.name}</span>
                        </div>
                        <span className="text-xs font-semibold text-gray-700">{s.value} <span className="font-normal text-gray-400">({pct}%)</span></span>
                      </div>
                      <div className="h-2.5 w-full bg-gray-100 rounded-full overflow-hidden">
                        <div className="h-full rounded-full transition-all" style={{ width: `${pct}%`, background: s.fill }} />
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </SectionCard>

    </div>
  );
}



