import { useState, useEffect } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
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 { Receipt, Search, Download, DollarSign, Home, FileText, CreditCard, AlertCircle } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { supabase } from "@/integrations/supabase/client";
import { format } from "date-fns";
import { parseLocalDate } from "@/lib/dateUtils";
import { generateLedgerStatement } from "@/components/unit-profile/UnitLedgerStatementPDF";
import { useToast } from "@/hooks/use-toast";

interface LedgerEntry {
  id: string;
  date: string;
  description: string | null;
  transaction_type: string;
  debit: number;
  credit: number;
}

export default function HomeownerLedgerPage() {
  const navigate = useNavigate();
  const { currentOwner, association, unit, loading: ctxLoading } = useHomeowner();
  const { toast } = useToast();
  const [entries, setEntries] = useState<LedgerEntry[]>([]);
  const [owners, setOwners] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");

  useEffect(() => {
    if (!currentOwner) {
      setLoading(false);
      return;
    }

    const fetchLedger = async () => {
      setLoading(true);
      const query = supabase
        .from("owner_ledger_entries")
        .select("*")
        .eq("is_archived", false)
        .order("date", { ascending: false });

      const [ledgerRes, ownersRes] = await Promise.all([
        unit?.id ? query.eq("unit_id", unit.id) : query.eq("owner_id", currentOwner.id),
        unit?.id
          ? supabase.from("owners").select("id, first_name, last_name, is_primary").eq("unit_id", unit.id).eq("status", "active")
          : Promise.resolve({ data: [currentOwner], error: null }),
      ]);

      if (!ledgerRes.error && ledgerRes.data) {
        setEntries(ledgerRes.data);
      }
      if (!ownersRes.error && ownersRes.data) {
        setOwners(ownersRes.data as any[]);
      }
      setLoading(false);
    };

    fetchLedger();
  }, [currentOwner, unit?.id]);

  const downloadStatement = () => {
    if (!unit || entries.length === 0) {
      toast({ variant: "destructive", title: "Statement unavailable", description: "No ledger activity to export." });
      return;
    }
    try {
      generateLedgerStatement({
        unitData: unit,
        owners: owners.length ? owners : [currentOwner],
        entries: [...entries].sort((a, b) => a.date.localeCompare(b.date)),
        associationName: association?.name,
      });
    } catch (error: any) {
      toast({ variant: "destructive", title: "Download failed", description: error.message || "Could not generate statement." });
    }
  };

  if (ctxLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!currentOwner) {
    return (
      <div className="text-center py-20 space-y-2">
        <AlertCircle className="h-10 w-10 text-muted-foreground/30 mx-auto" />
        <p className="text-lg font-medium text-foreground">No property linked to your account</p>
        <p className="text-sm text-muted-foreground">Please contact your property management company.</p>
      </div>
    );
  }

  const balance = currentOwner.balance ?? 0;
  const totalCharged = entries.reduce((sum, e) => sum + (e.debit || 0), 0);
  const totalPaid = entries.reduce((sum, e) => sum + (e.credit || 0), 0);
  const chargeCount = entries.filter((e) => e.debit > 0).length;
  const paymentCount = entries.filter((e) => e.credit > 0).length;
  const lastPayment = entries.find((e) => e.credit > 0);

  const propertyAddress = unit?.address || currentOwner.property_address || currentOwner.street_address || "—";

  // Filter entries
  const filteredEntries = entries.filter((e) => {
    if (typeFilter === "charge" && e.debit <= 0) return false;
    if (typeFilter === "payment" && e.credit <= 0) return false;
    if (search && !(e.description || "").toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  // Running balance calculation
  let runningBalance = 0;
  const entriesWithBalance = [...filteredEntries]
    .reverse()
    .map((e) => {
      runningBalance += (e.debit || 0) - (e.credit || 0);
      return { ...e, runningBalance };
    })
    .reverse();

  return (
    <div className="space-y-6">
      {/* Header */}
      <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">
            <Receipt className="h-6 w-6 text-primary" /> Account Ledger
          </h1>
          <div className="flex items-center gap-3 mt-1 text-sm text-muted-foreground flex-wrap">
            <span className="flex items-center gap-1">
              <Home className="h-3.5 w-3.5" /> {propertyAddress}
            </span>
            <span>·</span>
            <span>{association?.name || "—"}</span>
            {unit?.account_number && (
              <>
                <span>·</span>
                <span>#{unit.account_number}</span>
              </>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" className="gap-2" onClick={downloadStatement} disabled={entries.length === 0}>
            <Download className="h-4 w-4" /> Statement
          </Button>
          <Button onClick={() => navigate("/homeowner/payments")} className="gap-2">
            <DollarSign className="h-4 w-4" /> Make Payment
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className={`border-l-4 ${balance > 0 ? "border-l-warning" : "border-l-success"}`}>
          <CardContent className="p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground tracking-wide">Current Balance</p>
            <p className={`text-2xl font-bold mt-1 ${balance > 0 ? "text-warning" : "text-success"}`}>
              ${Math.abs(balance).toFixed(2)}
            </p>
            <p className="text-xs text-muted-foreground mt-0.5">
              {balance > 0 ? "Amount due" : balance < 0 ? "Credit" : "No balance"}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground tracking-wide">Last Payment</p>
            <p className="text-2xl font-bold text-foreground mt-1">
              {lastPayment ? `$${lastPayment.credit.toFixed(2)}` : "—"}
            </p>
            <p className="text-xs text-muted-foreground mt-0.5">
              {lastPayment ? format(parseLocalDate(lastPayment.date), "MMM d, yyyy") : "No payments recorded"}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground tracking-wide">Total Charged</p>
            <p className="text-2xl font-bold text-foreground mt-1">${totalCharged.toFixed(2)}</p>
            <p className="text-xs text-muted-foreground mt-0.5">{chargeCount} charge(s)</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-xs font-semibold uppercase text-muted-foreground tracking-wide">Total Paid</p>
            <p className="text-2xl font-bold text-success mt-1">${totalPaid.toFixed(2)}</p>
            <p className="text-xs text-muted-foreground mt-0.5">{paymentCount} payment(s)</p>
          </CardContent>
        </Card>
      </div>

      {/* Transaction History */}
      <Card>
        <CardContent className="p-0">
          {/* Filters row */}
          <div className="flex flex-wrap items-center gap-3 p-4 border-b border-border">
            <h2 className="text-base font-semibold text-foreground mr-auto">Transaction History</h2>
            <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>
            <Select value={typeFilter} onValueChange={setTypeFilter}>
              <SelectTrigger className="w-32 h-9">
                <SelectValue placeholder="All Types" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="charge">Charges</SelectItem>
                <SelectItem value="payment">Payments</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Table */}
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Description</TableHead>
                <TableHead>Type</TableHead>
                <TableHead className="text-right">Charge</TableHead>
                <TableHead className="text-right">Payment</TableHead>
                <TableHead className="text-right">Balance</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={6} 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>
              ) : entriesWithBalance.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-12">
                    <div className="flex flex-col items-center gap-2 text-muted-foreground">
                      <FileText className="h-8 w-8 opacity-40" />
                      <img
                        src="https://yqdefzjapnzabowsgoyd.supabase.co/storage/v1/object/public/company-assets/media/2da85a3d-35f9-4b78-853f-350c7c9a788b.png"
                        alt="Happy Cloud"
                        width="48"
                        className="h-16 w-16 object-contain"
                      />
                      <p className="text-sm">Nothing here yet!</p>
                    </div>
                  </TableCell>
                </TableRow>
              ) : (
                entriesWithBalance.map((entry) => (
                  <TableRow key={entry.id}>
                    <TableCell className="text-sm">{format(parseLocalDate(entry.date), "MMM d, yyyy")}</TableCell>
                    <TableCell className="text-sm">{entry.description || "—"}</TableCell>
                    <TableCell>
                      <Badge variant={entry.debit > 0 ? "destructive" : "default"} className="text-[11px]">
                        {entry.transaction_type || (entry.debit > 0 ? "Charge" : "Payment")}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right text-sm">
                      {entry.debit > 0 ? `$${entry.debit.toFixed(2)}` : "—"}
                    </TableCell>
                    <TableCell className="text-right text-sm text-success">
                      {entry.credit > 0 ? `$${entry.credit.toFixed(2)}` : "—"}
                    </TableCell>
                    <TableCell className="text-right text-sm font-medium">${entry.runningBalance.toFixed(2)}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Bottom Make Payment */}
      <div className="flex justify-end">
        <Button onClick={() => navigate("/homeowner/payments")} className="gap-2">
          <DollarSign className="h-4 w-4" /> Make Payment
        </Button>
      </div>
    </div>
  );
}
