import { useState, useEffect, useMemo } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { FileText, Search, Download, Filter } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { format, subDays } from "date-fns";
import { parseLocalDate } from "@/lib/dateUtils";
import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import { toast } from "sonner";

interface ChargeRow {
  id: string;
  date: string;
  description: string | null;
  transaction_type: string;
  debit: number;
  credit: number;
  owner_name: string;
  unit_number: string;
  association_name: string;
}

export default function LedgerChargesReportPage() {
  const [rows, setRows] = useState<ChargeRow[]>([]);
  const [associations, setAssociations] = useState<{ id: string; name: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState("");
  const [assocFilter, setAssocFilter] = useState("all");
  const [typeFilter, setTypeFilter] = useState("all");
  const [startDate, setStartDate] = useState(() => format(subDays(new Date(), 30), "yyyy-MM-dd"));
  const [endDate, setEndDate] = useState(() => format(new Date(), "yyyy-MM-dd"));

  useEffect(() => {
    supabase.from("associations").select("id, name").eq("status", "active").order("name")
      .then(({ data }) => { if (data) setAssociations(data); });
  }, []);

  const fetchData = async () => {
    setLoading(true);
    try {
      const allRows: ChargeRow[] = [];
      const pageSize = 1000;
      let from = 0;

      while (true) {
        let query = supabase
          .from("owner_ledger_entries")
          .select("id, date, description, transaction_type, debit, credit, owners(first_name, last_name), units(unit_number), associations(name)")
          .gte("date", startDate)
          .lte("date", endDate)
          .order("date", { ascending: false })
          .range(from, from + pageSize - 1);

        if (assocFilter !== "all") {
          query = query.eq("association_id", assocFilter);
        }

        const { data, error } = await query;
        if (error) throw error;
        if (!data || data.length === 0) break;

        for (const row of data) {
          const owner = row.owners as any;
          const unit = row.units as any;
          const assoc = row.associations as any;
          allRows.push({
            id: row.id,
            date: row.date,
            description: row.description,
            transaction_type: row.transaction_type,
            debit: row.debit,
            credit: row.credit,
            owner_name: owner ? `${owner.first_name || ""} ${owner.last_name || ""}`.trim() : "—",
            unit_number: unit?.unit_number || "—",
            association_name: assoc?.name || "—",
          });
        }

        if (data.length < pageSize) break;
        from += pageSize;
      }

      setRows(allRows);
    } catch (err: any) {
      toast.error("Failed to load charges: " + err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchData(); }, [startDate, endDate, assocFilter]);

  const filtered = useMemo(() => {
    return rows.filter((r) => {
      if (typeFilter === "charge" && r.debit <= 0) return false;
      if (typeFilter === "payment" && r.credit <= 0) return false;
      if (search) {
        const s = search.toLowerCase();
        if (
          !(r.description || "").toLowerCase().includes(s) &&
          !r.owner_name.toLowerCase().includes(s) &&
          !r.unit_number.toLowerCase().includes(s) &&
          !r.transaction_type.toLowerCase().includes(s)
        ) return false;
      }
      return true;
    });
  }, [rows, typeFilter, search]);

  const totalDebit = filtered.reduce((s, r) => s + (r.debit || 0), 0);
  const totalCredit = filtered.reduce((s, r) => s + (r.credit || 0), 0);

  const exportPdf = () => {
    if (filtered.length === 0) { toast.error("No data to export"); return; }
    const doc = new jsPDF({ orientation: "landscape", compress: true });
    doc.setFontSize(16);
    doc.text("Ledger Charges Report", 14, 18);
    doc.setFontSize(10);
    doc.text(`Date Range: ${format(parseLocalDate(startDate), "MMM d, yyyy")} – ${format(parseLocalDate(endDate), "MMM d, yyyy")}`, 14, 26);
    doc.text(`Generated: ${format(new Date(), "MMM d, yyyy h:mm a")}`, 14, 32);
    doc.text(`Records: ${filtered.length}`, 14, 38);

    autoTable(doc, {
      startY: 44,
      head: [["Date", "Association", "Unit", "Owner", "Description", "Type", "Charge", "Payment"]],
      body: filtered.map((r) => [
        format(parseLocalDate(r.date), "MM/dd/yyyy"),
        r.association_name,
        r.unit_number,
        r.owner_name,
        r.description || "—",
        r.transaction_type,
        r.debit > 0 ? `$${r.debit.toFixed(2)}` : "",
        r.credit > 0 ? `$${r.credit.toFixed(2)}` : "",
      ]),
      foot: [["", "", "", "", "", "Totals:", `$${totalDebit.toFixed(2)}`, `$${totalCredit.toFixed(2)}`]],
      theme: "grid",
      headStyles: { fillColor: [51, 65, 85] },
      footStyles: { fillColor: [241, 245, 249], textColor: [15, 23, 42], fontStyle: "bold" },
      styles: { fontSize: 8 },
      columnStyles: { 6: { halign: "right" }, 7: { halign: "right" } },
    });

    doc.save(`Ledger_Charges_Report_${format(new Date(), "yyyy-MM-dd")}.pdf`);
    toast.success("PDF downloaded");
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <FileText className="h-6 w-6 text-primary" /> Ledger Charges Report
          </h1>
          <p className="text-sm text-muted-foreground mt-1">View and export recent ledger charges across all units</p>
        </div>
        <Button onClick={exportPdf} variant="outline" className="gap-2">
          <Download className="h-4 w-4" /> Export PDF
        </Button>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-wrap items-end gap-4">
            <div className="space-y-1">
              <Label className="text-xs">Start Date</Label>
              <Input type="date" className="h-9 w-40" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">End Date</Label>
              <Input type="date" className="h-9 w-40" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Association</Label>
              <Select value={assocFilter} onValueChange={setAssocFilter}>
                <SelectTrigger className="w-48 h-9"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Associations</SelectItem>
                  {associations.map((a) => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Type</Label>
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger className="w-36 h-9"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Types</SelectItem>
                  <SelectItem value="charge">Charges Only</SelectItem>
                  <SelectItem value="payment">Payments Only</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="relative min-w-48">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input placeholder="Search..." className="pl-9 h-9" value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Summary */}
      <div className="grid grid-cols-3 gap-4">
        <Card><CardContent className="p-4">
          <p className="text-xs font-semibold uppercase text-muted-foreground tracking-wide">Records</p>
          <p className="text-2xl font-bold text-foreground mt-1">{filtered.length}</p>
        </CardContent></Card>
        <Card><CardContent className="p-4">
          <p className="text-xs font-semibold uppercase text-muted-foreground tracking-wide">Total Charges</p>
          <p className="text-2xl font-bold text-foreground mt-1">${totalDebit.toFixed(2)}</p>
        </CardContent></Card>
        <Card><CardContent className="p-4">
          <p className="text-xs font-semibold uppercase text-muted-foreground tracking-wide">Total Payments</p>
          <p className="text-2xl font-bold text-success mt-1">${totalCredit.toFixed(2)}</p>
        </CardContent></Card>
      </div>

      {/* Table */}
      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Association</TableHead>
                <TableHead>Unit</TableHead>
                <TableHead>Owner</TableHead>
                <TableHead>Description</TableHead>
                <TableHead>Type</TableHead>
                <TableHead className="text-right">Charge</TableHead>
                <TableHead className="text-right">Payment</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-12">
                    <div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto" />
                  </TableCell>
                </TableRow>
              ) : filtered.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-12 text-muted-foreground">
                    <Filter className="h-8 w-8 opacity-40 mx-auto mb-2" />
                    <p className="text-sm">No entries found for the selected filters.</p>
                  </TableCell>
                </TableRow>
              ) : (
                filtered.map((r) => (
                  <TableRow key={r.id}>
                    <TableCell className="text-sm">{format(parseLocalDate(r.date), "MMM d, yyyy")}</TableCell>
                    <TableCell className="text-sm">{r.association_name}</TableCell>
                    <TableCell className="text-sm">{r.unit_number}</TableCell>
                    <TableCell className="text-sm">{r.owner_name}</TableCell>
                    <TableCell className="text-sm">{r.description || "—"}</TableCell>
                    <TableCell>
                      <Badge variant={r.debit > 0 ? "destructive" : "default"} className="text-[11px]">
                        {r.transaction_type}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right text-sm">{r.debit > 0 ? `$${r.debit.toFixed(2)}` : ""}</TableCell>
                    <TableCell className="text-right text-sm text-success">{r.credit > 0 ? `$${r.credit.toFixed(2)}` : ""}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
