import { useState, useEffect, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { format, parseISO, subDays } from "date-fns";
import {
  Search, Loader2, AlertCircle, RefreshCw, Clock,
  ChevronLeft, ChevronRight, ArrowUpDown, ChevronUp, ChevronDown
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useNavigate } from "react-router-dom";

interface LedgerEntry {
  id: string;
  unit_id: string;
  owner_id: string | null;
  date: string;
  description: string | null;
  transaction_type: string | null;
  debit: number | null;
  credit: number | null;
  created_at: string;
  updated_at: string | null;
  reference_id: string | null;
  source: string | null;
  units?: { unit_number: string; associations?: { name: string } } | null;
  owners?: { first_name: string; last_name: string } | null;
}

export default function RecentLedgerUpdatesPage() {
  const navigate = useNavigate();
  const [entries, setEntries] = useState<LedgerEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [daysBack, setDaysBack] = useState("7");
  const [sourceFilter, setSourceFilter] = useState("all");
  const [sortConfig, setSortConfig] = useState({ key: "created_at", direction: "desc" as "asc" | "desc" });
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 25;

  useEffect(() => {
    fetchEntries();
  }, [daysBack]);

  const fetchEntries = async () => {
    setLoading(true);
    setError(null);
    try {
      const since = subDays(new Date(), parseInt(daysBack)).toISOString();
      
      // Fetch in pages to avoid the 1000-row limit
      let allData: any[] = [];
      let from = 0;
      const batchSize = 1000;
      let hasMore = true;

      while (hasMore) {
        const { data, error: fetchError } = await supabase
          .from("owner_ledger_entries")
          .select("*, units(unit_number, associations(name)), owners(first_name, last_name)")
          .gte("created_at", since)
          .order("created_at", { ascending: false })
          .range(from, from + batchSize - 1);

        if (fetchError) throw fetchError;
        allData = [...allData, ...(data || [])];
        hasMore = (data?.length || 0) === batchSize;
        from += batchSize;
      }

      setEntries(allData);
    } catch (err: any) {
      console.error("Error fetching recent updates:", err);
      setError("Unable to load recent updates. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const sources = useMemo(() => {
    const s = new Set(entries.map(e => e.source || "manual"));
    return Array.from(s).sort();
  }, [entries]);

  const handleSort = (key: string) => {
    setSortConfig(c => c.key === key ? { key, direction: c.direction === "asc" ? "desc" : "asc" } : { key, direction: "desc" });
  };

  const filteredAndSorted = useMemo(() => {
    let result = [...entries];
    if (sourceFilter !== "all") {
      result = result.filter(e => (e.source || "manual") === sourceFilter);
    }
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      result = result.filter(e =>
        (e.description || "").toLowerCase().includes(q) ||
        (e.transaction_type || "").toLowerCase().includes(q) ||
        (e.units?.unit_number || "").toLowerCase().includes(q) ||
        (e.units?.associations?.name || "").toLowerCase().includes(q) ||
        (`${e.owners?.first_name || ""} ${e.owners?.last_name || ""}`).toLowerCase().includes(q)
      );
    }
    result.sort((a, b) => {
      let vA = a[sortConfig.key as keyof LedgerEntry] ?? "";
      let vB = b[sortConfig.key as keyof LedgerEntry] ?? "";
      if (vA < vB) return sortConfig.direction === "asc" ? -1 : 1;
      if (vA > vB) return sortConfig.direction === "asc" ? 1 : -1;
      return 0;
    });
    return result;
  }, [entries, sourceFilter, searchQuery, sortConfig]);

  const totalPages = Math.ceil(filteredAndSorted.length / pageSize) || 1;
  const paginatedData = filteredAndSorted.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  useEffect(() => {
    if (currentPage > totalPages) setCurrentPage(totalPages);
  }, [totalPages, currentPage]);

  const totalDebits = filteredAndSorted.reduce((s, e) => s + Number(e.debit || 0), 0);
  const totalCredits = filteredAndSorted.reduce((s, e) => s + Number(e.credit || 0), 0);

  const SortIcon = ({ columnKey }: { columnKey: string }) => {
    if (sortConfig.key !== columnKey) return <ArrowUpDown className="ml-1 h-3.5 w-3.5 text-muted-foreground" />;
    return sortConfig.direction === "asc" ? <ChevronUp className="ml-1 h-3.5 w-3.5" /> : <ChevronDown className="ml-1 h-3.5 w-3.5" />;
  };

  const sourceLabel = (src: string | null) => {
    const s = src || "manual";
    const map: Record<string, { label: string; variant: "default" | "secondary" | "outline" }> = {
      buildium: { label: "Buildium Sync", variant: "default" },
      buildium_pushed: { label: "Pushed to Buildium", variant: "secondary" },
      manual: { label: "Manual", variant: "outline" },
      csv_import: { label: "CSV Import", variant: "secondary" },
      bulk_charge: { label: "Bulk Charge", variant: "secondary" },
      auto_interest: { label: "Auto Interest", variant: "secondary" },
      auto_late_fee: { label: "Auto Late Fee", variant: "secondary" },
    };
    const info = map[s] || { label: s, variant: "outline" as const };
    return <Badge variant={info.variant} className="text-xs font-normal">{info.label}</Badge>;
  };

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center py-24 text-muted-foreground">
        <Loader2 className="w-8 h-8 animate-spin text-primary mb-4" />
        <p>Loading recent updates...</p>
      </div>
    );
  }

  return (
    <div className="p-4 md:p-6 max-w-[1400px] mx-auto space-y-6">
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <Clock className="h-6 w-6 text-primary" /> Recent Ledger Updates
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            All transactions recently added or synced to owner ledgers.
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchEntries} className="gap-2">
          <RefreshCw className="h-4 w-4" /> Refresh
        </Button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card>
          <CardContent className="pt-5 pb-4">
            <p className="text-sm text-muted-foreground">Total Entries</p>
            <p className="text-2xl font-bold text-foreground">{filteredAndSorted.length.toLocaleString()}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5 pb-4">
            <p className="text-sm text-muted-foreground">Total Charges</p>
            <p className="text-2xl font-bold text-destructive">${totalDebits.toFixed(2)}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5 pb-4">
            <p className="text-sm text-muted-foreground">Total Payments / Credits</p>
            <p className="text-2xl font-bold text-emerald-600">${totalCredits.toFixed(2)}</p>
          </CardContent>
        </Card>
      </div>

      {error && (
        <div className="flex items-center gap-2 text-destructive bg-destructive/10 rounded-md p-3">
          <AlertCircle className="h-5 w-5" /> {error}
        </div>
      )}

      <Card className="shadow-md border">
        <CardHeader className="bg-muted/50 border-b pb-5">
          <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
            <div>
              <CardTitle className="text-lg">Transaction Log</CardTitle>
              <CardDescription>Filtered by creation date</CardDescription>
            </div>
            <div className="flex flex-col sm:flex-row gap-3">
              <div className="relative">
                <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search..."
                  value={searchQuery}
                  onChange={e => { setSearchQuery(e.target.value); setCurrentPage(1); }}
                  className="pl-9 w-full sm:w-[200px]"
                />
              </div>
              <Select value={daysBack} onValueChange={v => { setDaysBack(v); setCurrentPage(1); }}>
                <SelectTrigger className="w-[150px]"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">Last 24 hours</SelectItem>
                  <SelectItem value="3">Last 3 days</SelectItem>
                  <SelectItem value="7">Last 7 days</SelectItem>
                  <SelectItem value="14">Last 14 days</SelectItem>
                  <SelectItem value="30">Last 30 days</SelectItem>
                  <SelectItem value="90">Last 90 days</SelectItem>
                </SelectContent>
              </Select>
              {sources.length > 1 && (
                <Select value={sourceFilter} onValueChange={v => { setSourceFilter(v); setCurrentPage(1); }}>
                  <SelectTrigger className="w-[160px]"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Sources</SelectItem>
                    {sources.map(s => (
                      <SelectItem key={s} value={s}>{s}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-muted/50">
                <TableRow>
                  <TableHead className="py-3 px-4">
                    <Button variant="ghost" onClick={() => handleSort("created_at")} className="hover:bg-muted -ml-3 h-8 flex items-center text-xs uppercase tracking-wider font-semibold">
                      Added <SortIcon columnKey="created_at" />
                    </Button>
                  </TableHead>
                  <TableHead className="py-3 px-4">
                    <Button variant="ghost" onClick={() => handleSort("date")} className="hover:bg-muted -ml-3 h-8 flex items-center text-xs uppercase tracking-wider font-semibold">
                      Txn Date <SortIcon columnKey="date" />
                    </Button>
                  </TableHead>
                  <TableHead className="py-3 px-4 text-xs uppercase tracking-wider font-semibold">Association</TableHead>
                  <TableHead className="py-3 px-4 text-xs uppercase tracking-wider font-semibold">Unit</TableHead>
                  <TableHead className="py-3 px-4 text-xs uppercase tracking-wider font-semibold">Owner</TableHead>
                  <TableHead className="py-3 px-4 text-xs uppercase tracking-wider font-semibold">Description</TableHead>
                  <TableHead className="py-3 px-4 text-xs uppercase tracking-wider font-semibold">Source</TableHead>
                  <TableHead className="py-3 px-4 text-xs uppercase tracking-wider font-semibold text-right">Charge</TableHead>
                  <TableHead className="py-3 px-4 text-xs uppercase tracking-wider font-semibold text-right">Payment</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paginatedData.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="h-32 text-center text-muted-foreground">
                      No recent transactions found.
                    </TableCell>
                  </TableRow>
                ) : (
                  paginatedData.map(e => (
                    <TableRow
                      key={e.id}
                      className="hover:bg-muted/30 transition-colors border-b cursor-pointer"
                      onClick={() => e.unit_id && navigate(`/dashboard/units/${e.unit_id}`)}
                    >
                      <TableCell className="py-3 px-4 text-xs text-muted-foreground whitespace-nowrap">
                        {format(parseISO(e.created_at), "MMM d, h:mm a")}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-sm whitespace-nowrap">
                        {e.date ? format(parseISO(e.date), "MMM d, yyyy") : "-"}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-sm">
                        {(e.units as any)?.associations?.name || "-"}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-sm font-medium">
                        {(e.units as any)?.unit_number || "-"}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-sm">
                        {e.owners ? `${(e.owners as any).first_name} ${(e.owners as any).last_name}` : "-"}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-sm max-w-[250px] truncate">
                        {e.description || "-"}
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        {sourceLabel(e.source)}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-right text-sm font-medium">
                        {Number(e.debit || 0) > 0 ? `$${Number(e.debit).toFixed(2)}` : ""}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-right text-sm font-medium text-emerald-600">
                        {Number(e.credit || 0) > 0 ? `$${Number(e.credit).toFixed(2)}` : ""}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {totalPages > 1 && (
            <div className="flex items-center justify-between px-6 py-4 border-t bg-muted/50">
              <div className="text-sm text-muted-foreground">
                Showing {(currentPage - 1) * pageSize + 1} to {Math.min(currentPage * pageSize, filteredAndSorted.length)} of {filteredAndSorted.length}
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1}>
                  <ChevronLeft className="w-4 h-4 mr-1" /> Prev
                </Button>
                <div className="flex items-center justify-center px-4 text-sm font-medium border rounded-md">
                  {currentPage} / {totalPages}
                </div>
                <Button variant="outline" size="sm" onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages}>
                  Next <ChevronRight className="w-4 h-4 ml-1" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
