import { useState, useEffect, useMemo, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import {
  Search, Building2, User, Wallet, ArrowUpDown, PlusCircle, AlertCircle, Trash2,
  Loader2, RefreshCw, Ban, Pencil, FileStack, FileText, Download, CheckSquare, Printer,
  MoreHorizontal, RotateCcw, CreditCard, Replace, Archive, ArchiveRestore, Upload
} from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { generateLedgerStatement } from "./UnitLedgerStatementPDF";
import UnitLedgerInvoiceDialog from "./UnitLedgerInvoiceDialog";
import LedgerCSVImportDialog from "@/components/LedgerCSVImportDialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { useToast } from "@/hooks/use-toast";
import { format } from "date-fns";
import { parseLocalDate, todayLocal } from "@/lib/dateUtils";
import { useAuth } from "@/contexts/AuthContext";
import UnitLedgerTransactionForm from "./UnitLedgerTransactionForm";
import UnitFeeExclusionsCard from "./UnitFeeExclusionsCard";

interface Props {
  unitId: string;
  associationId?: string;
}

export default function UnitLedgerView({ unitId, associationId }: Props) {
  const { toast } = useToast();
  const navigate = useNavigate();
  const { user, isAdmin, isStaff } = useAuth();
  const canEdit = isAdmin || isStaff;
  const [buildiumSyncing, setBuildiumSyncing] = useState<null | "pull" | "push">(null);

  const handleBuildiumSync = async (mode: "pull" | "push") => {
    setBuildiumSyncing(mode);
    try {
      if (mode === "pull") {
        const { data, error } = await supabase.functions.invoke("buildium-import-stage", {
          body: { kinds: ["ledger_entry"], unitId },
        });
        if (error) throw error;
        toast({
          title: "Pulled for review",
          description: `${data?.inserted ?? 0} ledger entries staged. Approve them to apply.`,
        });
        if (data?.batch_id) {
          navigate(`/dashboard/settings/buildium/review?batch_id=${data.batch_id}`);
        }
      } else {
        const { data, error } = await supabase.functions.invoke("buildium-sync", {
          body: { syncType: "push_all", unitId },
        });
        if (error) throw error;
        toast({ title: "Pushed to Buildium", description: "Sync completed successfully." });
        await fetchLedger(true);
      }
    } catch (err: any) {
      console.error("Buildium sync error:", err);
      toast({
        variant: "destructive",
        title: "Buildium sync failed",
        description: err?.message || "Unable to sync with Buildium.",
      });
    } finally {
      setBuildiumSyncing(null);
    }
  };

  const [unitData, setUnitData] = useState<any>(null);
  const [owners, setOwners] = useState<any[]>([]);
  const [entries, setEntries] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const [searchQuery, setSearchQuery] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

  const [formOpen, setFormOpen] = useState(false);
  const [editingEntry, setEditingEntry] = useState<any>(null);
  const [deleteEntry, setDeleteEntry] = useState<any>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [errorState, setErrorState] = useState<string | null>(null);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
  const [invoiceOpen, setInvoiceOpen] = useState(false);
  const [bulkTypeOpen, setBulkTypeOpen] = useState(false);
  const [bulkNewType, setBulkNewType] = useState("");
  const [bulkUpdating, setBulkUpdating] = useState(false);

  const TRANSACTION_TYPES = [
    { value: "assessment", label: "Assessment" },
    { value: "late_fee", label: "Late Fee" },
    { value: "interest", label: "Interest" },
    { value: "admin_fee", label: "Admin Fee" },
    { value: "legal_fee", label: "Legal Fee" },
    { value: "violation", label: "Violation Fine" },
    { value: "bank_fee", label: "Bank Fee" },
    { value: "special_assessment", label: "Special Assessment" },
    { value: "payment", label: "Payment" },
    { value: "Prepayment", label: "Prepayment" },
    { value: "Refund", label: "Refund" },
    { value: "other", label: "Other" },
  ];

  const fetchLedger = useCallback(async (silent = false) => {
    if (!unitId) return;
    if (!silent) setLoading(true);
    else setRefreshing(true);
    setErrorState(null);

    try {
      const [unitRes, ownersRes, entriesRes] = await Promise.all([
        supabase.from("units").select("*, associations(id, name, zoho_organization_id)").eq("id", unitId).single(),
        supabase.from("owners").select("*").eq("status", "active").eq("unit_id", unitId),
        // Active ledger: only entries belonging to currently active owners and not manually archived.
        // Entries from archived (moved-out) owners or marked as archived are preserved in Transaction History.
        supabase
          .from("owner_ledger_entries")
          .select("*, owners!inner(status)")
          .eq("unit_id", unitId)
          .eq("owners.status", "active")
          .eq("is_archived", false)
          .order("date", { ascending: true })
          .order("created_at", { ascending: true }),
      ]);

      if (unitRes.data) setUnitData(unitRes.data);
      if (ownersRes.data) setOwners(ownersRes.data);
      if (entriesRes.error) throw entriesRes.error;
      setEntries(entriesRes.data || []);
    } catch (err: any) {
      console.error("[UnitLedgerView] Error:", err);
      setErrorState(err.message || "Failed to load ledger data");
      toast({ variant: "destructive", title: "Error", description: "Failed to load ledger data." });
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [unitId, toast]);

  useEffect(() => { fetchLedger(); }, [fetchLedger]);

  // Realtime subscription
  useEffect(() => {
    if (!unitId) return;
    const channel = supabase
      .channel(`ledger_${unitId}`)
      .on("postgres_changes", { event: "*", schema: "public", table: "owner_ledger_entries", filter: `unit_id=eq.${unitId}` }, () => fetchLedger(true))
      .subscribe();
    return () => { supabase.removeChannel(channel); };
  }, [unitId, fetchLedger]);

  const handleDelete = async () => {
    if (!deleteEntry) return;
    setIsDeleting(true);
    try {
      const { error } = await supabase.from("owner_ledger_entries").delete().eq("id", deleteEntry.id);
      if (error) throw error;
      toast({ title: "Entry Deleted", description: "The ledger entry has been removed." });
      fetchLedger(true);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Delete Failed", description: err.message });
    } finally {
      setIsDeleting(false);
      setDeleteEntry(null);
    }
  };

  const handleBulkChangeType = async () => {
    if (selectedIds.size === 0 || !bulkNewType) return;
    setBulkUpdating(true);
    try {
      const { error } = await supabase
        .from("owner_ledger_entries")
        .update({ transaction_type: bulkNewType })
        .in("id", [...selectedIds]);
      if (error) throw error;
      toast({ title: `${selectedIds.size} entries updated to "${bulkNewType.replace(/_/g, " ")}"` });
      setSelectedIds(new Set());
      setBulkTypeOpen(false);
      setBulkNewType("");
      fetchLedger(true);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Bulk Update Failed", description: err.message });
    } finally {
      setBulkUpdating(false);
    }
  };

  const handleBulkDelete = async () => {
    if (selectedIds.size === 0) return;
    setIsDeleting(true);
    try {
      const { error } = await supabase.from("owner_ledger_entries").delete().in("id", [...selectedIds]);
      if (error) throw error;
      toast({ title: `${selectedIds.size} entries deleted` });
      setSelectedIds(new Set());
      setBulkDeleteOpen(false);
      fetchLedger(true);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Bulk Delete Failed", description: err.message });
    } finally {
      setIsDeleting(false);
    }
  };

  const handleArchiveEntry = async (entry: any, archive: boolean) => {
    try {
      const { error } = await supabase
        .from("owner_ledger_entries")
        .update({ is_archived: archive })
        .eq("id", entry.id);
      if (error) throw error;
      toast({
        title: archive ? "Transaction Archived" : "Transaction Restored",
        description: archive
          ? "Hidden from active ledger. Still visible in Transaction History."
          : "Transaction is back on the active ledger.",
      });
      fetchLedger(true);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Archive Failed", description: err.message });
    }
  };

  const handleBulkArchive = async (archive: boolean) => {
    if (selectedIds.size === 0) return;
    try {
      const { error } = await supabase
        .from("owner_ledger_entries")
        .update({ is_archived: archive })
        .in("id", [...selectedIds]);
      if (error) throw error;
      toast({
        title: `${selectedIds.size} ${archive ? "archived" : "restored"}`,
        description: archive
          ? "Hidden from active ledger. Still visible in Transaction History."
          : "Transactions are back on the active ledger.",
      });
      setSelectedIds(new Set());
      fetchLedger(true);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Bulk Archive Failed", description: err.message });
    }
  };

  const toggleSelect = (id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectAll = () => {
    if (selectedIds.size === processedEntries.length) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(processedEntries.map((e) => e.id)));
    }
  };

  const handleEdit = (entry: any) => {
    setEditingEntry(entry);
    setFormOpen(true);
  };

  const handleRefund = async (entry: any) => {
    const amount = Number(entry.debit || 0) || Number(entry.credit || 0);
    if (!amount) return;
    try {
      const isDebit = Number(entry.debit || 0) > 0;
      await supabase.from("owner_ledger_entries").insert({
        unit_id: unitId,
        association_id: entry.association_id,
        owner_id: entry.owner_id,
        date: todayLocal(),
        description: `Refund: ${entry.description || ""}`.trim(),
        transaction_type: "Refund",
        debit: isDebit ? 0 : amount,
        credit: isDebit ? amount : 0,
        created_by: user?.id,
      });
      toast({ title: "Refund Posted", description: `$${amount.toFixed(2)} refund entry created.` });
      fetchLedger(true);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Refund Failed", description: err.message });
    }
  };

  const handleConvertToPrepayment = async (entry: any) => {
    try {
      const amount = Number(entry.debit || 0) || Number(entry.credit || 0);
      // Ensure prepayment is always stored as a credit
      const { error } = await supabase.from("owner_ledger_entries").update({
        transaction_type: "Prepayment",
        description: `Prepayment: ${(entry.description || "").replace(/^Prepayment:\s*/i, "")}`.trim(),
        debit: 0,
        credit: amount,
      }).eq("id", entry.id);
      if (error) throw error;

      toast({ title: "Converted to Prepayment", description: "Transaction updated to account credit." });

      // Auto-apply prepayment against outstanding balance
      await autoApplyPrepayment(entry.id, amount, entry.association_id, entry.owner_id);
      fetchLedger(true);
    } catch (err: any) {
      toast({ variant: "destructive", title: "Conversion Failed", description: err.message });
    }
  };

  const autoApplyPrepayment = async (prepaymentEntryId: string, creditAmount: number, assocId?: string, ownerId?: string) => {
    if (creditAmount <= 0) return;
    try {
      // Get all outstanding charges (debits with no offsetting application yet)
      // We recalculate: sum debits - sum credits = outstanding per-entry isn't tracked,
      // so we apply against the total outstanding balance by creating an application entry.
      const { data: allEntries } = await supabase
        .from("owner_ledger_entries")
        .select("*")
        .eq("unit_id", unitId)
        .eq("is_archived", false)
        .order("date", { ascending: true })
        .order("created_at", { ascending: true });

      if (!allEntries) return;

      const totalBalance = allEntries.reduce(
        (acc: number, e: any) => acc + Number(e.debit || 0) - Number(e.credit || 0),
        0
      );

      // After conversion the prepayment credit is already included, so totalBalance
      // reflects the net. If balance is still positive (charges outstanding),
      // no extra entry needed — the credit is naturally offsetting.
      // If balance went negative (overpayment), the excess stays as unapplied credit.
      // We just notify the user of the application.
      if (totalBalance < 0) {
        // Balance is negative = full credit applied with excess
        const applied = creditAmount + totalBalance; // totalBalance is negative
        if (applied > 0) {
          toast({
            title: "Prepayment Applied",
            description: `$${applied.toFixed(2)} applied to outstanding balance. $${Math.abs(totalBalance).toFixed(2)} remains as unapplied credit.`,
          });
        }
      } else if (totalBalance === 0) {
        toast({
          title: "Prepayment Fully Applied",
          description: `$${creditAmount.toFixed(2)} fully offset the outstanding balance.`,
        });
      } else {
        // Balance still positive = partial application
        toast({
          title: "Prepayment Applied",
          description: `$${creditAmount.toFixed(2)} applied. Remaining balance: $${totalBalance.toFixed(2)}.`,
        });
      }
    } catch (err) {
      console.error("Auto-apply prepayment error:", err);
    }
  };

  const processedEntries = useMemo(() => {
    let result = [...entries];
    let runningBalance = 0;

    // Calculate running balance (debit increases, credit decreases)
    result.forEach((e) => {
      runningBalance += Number(e.debit || 0) - Number(e.credit || 0);
      e._runningBalance = runningBalance;
    });

    // Filter by type
    if (typeFilter === "debit") result = result.filter((e) => Number(e.debit || 0) > 0);
    else if (typeFilter === "credit") result = result.filter((e) => Number(e.credit || 0) > 0);

    // Search
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      result = result.filter((e) => (e.description || "").toLowerCase().includes(q) || (e.transaction_type || "").toLowerCase().includes(q));
    }

    if (sortOrder === "desc") result.reverse();
    return result;
  }, [entries, searchQuery, typeFilter, sortOrder]);

  const totalBalance = entries.reduce((acc, e) => acc + Number(e.debit || 0) - Number(e.credit || 0), 0);
  const primaryOwner = owners.find((o) => o.is_primary) || owners[0];

  if (errorState) {
    return (
      <Alert variant="destructive" className="m-6">
        <AlertCircle className="h-4 w-4" />
        <AlertTitle>Error Loading Ledger Data</AlertTitle>
        <AlertDescription>{errorState}</AlertDescription>
        <Button variant="outline" className="mt-4" onClick={() => fetchLedger(false)}>Retry</Button>
      </Alert>
    );
  }

  return (
    <div className="space-y-6 pb-12">
      {/* Top Actions */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          {refreshing && (
            <span className="text-xs text-primary flex items-center font-medium animate-pulse bg-primary/10 px-2 py-1 rounded-md">
              <Loader2 className="w-3 h-3 mr-1.5 animate-spin" /> Syncing...
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => fetchLedger(true)} title="Refresh Data">
            <RefreshCw className={`w-4 h-4 ${refreshing ? "animate-spin" : ""}`} />
          </Button>
          {canEdit && (
            <>
              <Button
                variant="outline"
                onClick={() => handleBuildiumSync("pull")}
                disabled={buildiumSyncing !== null}
                title="Pull this unit's ledger from Buildium for review"
              >
                {buildiumSyncing === "pull" ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
                Pull from Buildium
              </Button>
              <Button
                variant="outline"
                onClick={() => handleBuildiumSync("push")}
                disabled={buildiumSyncing !== null}
                title="Push this unit's local ledger entries to Buildium"
              >
                {buildiumSyncing === "push" ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Upload className="w-4 h-4 mr-2" />}
                Push to Buildium
              </Button>
            </>
          )}
          <Button
            variant="outline"
            onClick={() =>
              generateLedgerStatement({
                unitData,
                owners,
                entries,
                associationName: unitData?.associations?.name || "Association",
              })
            }
            disabled={loading || entries.length === 0}
          >
            <Printer className="w-4 h-4 mr-2" /> Print Statement
          </Button>
          {canEdit && (
            <>
              <Button
                variant="outline"
                onClick={() => setInvoiceOpen(true)}
                disabled={loading || !unitData}
              >
                <FileText className="w-4 h-4 mr-2" /> Generate Invoice
              </Button>
              <LedgerCSVImportDialog
                unitId={unitId}
                associationId={associationId}
                onSuccess={() => fetchLedger(true)}
              />
              <Button onClick={() => { setEditingEntry(null); setFormOpen(true); }}>
                <PlusCircle className="w-4 h-4 mr-2" /> Add Transaction
              </Button>
            </>
          )}
        </div>
      </div>

      {/* Balance Cards */}
      {!loading && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <Card className={`text-white border-0 shadow-lg ${totalBalance > 0 ? "bg-destructive" : totalBalance < 0 ? "bg-emerald-600" : "bg-muted-foreground"}`}>
            <CardContent className="p-6">
              <p className="text-white/90 font-semibold text-sm tracking-wider mb-2">A/R BALANCE</p>
              <h2 className="text-4xl font-bold">
                ${Math.abs(totalBalance).toFixed(2)}
                {totalBalance < 0 && <span className="text-xl ml-1 font-medium opacity-80">(CR)</span>}
              </h2>
            </CardContent>
          </Card>

          <Card className="shadow-md border">
            <CardContent className="p-6 flex items-start gap-3">
              <div className="p-2.5 bg-primary/10 text-primary rounded-lg"><Building2 className="w-5 h-5" /></div>
              <div>
                <p className="text-sm text-muted-foreground font-medium uppercase tracking-wider">{unitData?.associations?.name || "Association"}</p>
                <p className="text-xl font-bold mt-1">Unit {unitData?.unit_number || "N/A"}</p>
                <p className="text-sm text-muted-foreground mt-0.5">{unitData?.address || ""}</p>
              </div>
            </CardContent>
          </Card>

          <Card className="shadow-md border">
            <CardContent className="p-6 flex items-start gap-3">
              <div className="p-2.5 bg-muted rounded-lg"><User className="w-5 h-5" /></div>
              <div>
                <p className="text-sm text-muted-foreground font-medium uppercase tracking-wider">Owner</p>
                <p className="text-lg font-semibold mt-1">{primaryOwner ? `${primaryOwner.first_name} ${primaryOwner.last_name}` : "Unassigned"}</p>
                {primaryOwner?.email && <p className="text-sm text-primary mt-0.5">{primaryOwner.email}</p>}
                {primaryOwner?.account_number && <p className="text-sm text-muted-foreground">Acc: {primaryOwner.account_number}</p>}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Fee Exclusions */}
      {unitId && (unitData?.associations?.id || associationId) && (
        <UnitFeeExclusionsCard
          unitId={unitId}
          associationId={unitData?.associations?.id || associationId || ""}
          canEdit={canEdit}
        />
      )}

      {/* Transaction Table */}
      <Card className="shadow-md border rounded-xl overflow-hidden">
        <CardHeader className="p-6 border-b bg-muted/50">
          <div className="flex flex-col xl:flex-row justify-between items-start xl:items-center gap-4">
            <CardTitle className="text-xl font-bold flex items-center gap-2">
              <FileStack className="w-5 h-5 text-primary" /> Transaction History
            </CardTitle>
            <div className="flex flex-wrap items-center gap-3 w-full xl:w-auto">
              <div className="relative flex-1 min-w-[200px] md:max-w-xs">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input placeholder="Search description..." className="pl-9 h-10" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
              </div>
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger className="h-10 w-[140px]"><SelectValue placeholder="All" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Types</SelectItem>
                  <SelectItem value="debit">Charges (Debit)</SelectItem>
                  <SelectItem value="credit">Payments (Credit)</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {canEdit && selectedIds.size > 0 && (
            <div className="flex items-center gap-3 px-4 py-3 bg-destructive/5 border-b">
              <CheckSquare className="w-4 h-4 text-destructive" />
              <span className="text-sm font-medium">{selectedIds.size} selected</span>
              <Button variant="outline" size="sm" className="ml-auto gap-1.5" onClick={() => { setBulkNewType(""); setBulkTypeOpen(true); }}>
                <Replace className="w-3.5 h-3.5" /> Change Type
              </Button>
              <Button variant="outline" size="sm" className="gap-1.5" onClick={() => handleBulkArchive(true)}>
                <Archive className="w-3.5 h-3.5" /> Archive
              </Button>
              <Button variant="destructive" size="sm" className="gap-1.5" onClick={() => setBulkDeleteOpen(true)}>
                <Trash2 className="w-3.5 h-3.5" /> Delete Selected
              </Button>
              <Button variant="ghost" size="sm" onClick={() => setSelectedIds(new Set())}>Clear</Button>
            </div>
          )}
          <TooltipProvider>
            <Table>
              <TableHeader className="bg-muted/50 border-b">
                <TableRow>
                  {canEdit && (
                    <TableHead className="w-10 py-4 pl-4">
                      <Checkbox
                        checked={processedEntries.length > 0 && selectedIds.size === processedEntries.length}
                        onCheckedChange={toggleSelectAll}
                      />
                    </TableHead>
                  )}
                  <TableHead className="w-32 py-4">
                    <Button variant="ghost" onClick={() => setSortOrder(sortOrder === "desc" ? "asc" : "desc")} className="h-8 -ml-3 px-3 text-xs uppercase tracking-wider font-bold">
                      Date <ArrowUpDown className="ml-2 h-3 w-3" />
                    </Button>
                  </TableHead>
                  <TableHead className="font-bold text-xs uppercase tracking-wider py-4">Description</TableHead>
                  <TableHead className="font-bold text-xs uppercase tracking-wider py-4">Type</TableHead>
                  <TableHead className="font-bold text-right text-xs uppercase tracking-wider py-4">Amount</TableHead>
                  <TableHead className="font-bold text-right text-xs uppercase tracking-wider py-4">Balance</TableHead>
                  {canEdit && <TableHead className="w-28 py-4 text-right text-xs font-bold uppercase tracking-wider pr-6">Actions</TableHead>}
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  Array.from({ length: 5 }).map((_, i) => (
                    <TableRow key={i} className="border-b">
                      <TableCell className="py-4"><Skeleton className="h-4 w-24" /></TableCell>
                      <TableCell className="py-4"><Skeleton className="h-4 w-48" /></TableCell>
                      <TableCell className="py-4"><Skeleton className="h-4 w-20" /></TableCell>
                      <TableCell className="py-4"><Skeleton className="h-4 w-16 ml-auto" /></TableCell>
                      <TableCell className="py-4"><Skeleton className="h-4 w-20 ml-auto" /></TableCell>
                      {canEdit && <TableCell className="py-4" />}
                    </TableRow>
                  ))
                ) : processedEntries.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={canEdit ? 6 : 5} className="h-48 text-center">
                      <div className="flex flex-col items-center justify-center text-muted-foreground">
                        <Wallet className="h-12 w-12 opacity-30 mb-3" />
                        <p className="text-base font-medium">No transactions yet</p>
                        <p className="text-sm mt-1 mb-4">Record the first transaction to get started.</p>
                        {canEdit && (
                          <Button onClick={() => { setEditingEntry(null); setFormOpen(true); }}>
                            <PlusCircle className="w-4 h-4 mr-2" /> Add Transaction
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  processedEntries.map((e) => {
                    const isDebit = Number(e.debit || 0) > 0;
                    const isPrepayment = e.transaction_type === "Prepayment";
                    const amount = isDebit ? Number(e.debit) : Number(e.credit);

                    const badgeClass = isPrepayment
                      ? "bg-blue-50 text-blue-700"
                      : isDebit
                        ? "bg-destructive/10 text-destructive"
                        : "bg-emerald-50 text-emerald-700";
                    const badgeLabel = isPrepayment ? "Prepayment" : isDebit ? "Charge" : "Payment";

                    return (
                      <TableRow key={e.id} className={`hover:bg-muted/30 transition-colors border-b last:border-0 ${selectedIds.has(e.id) ? "bg-primary/5" : ""}`}>
                        {canEdit && (
                          <TableCell className="py-4 pl-4">
                            <Checkbox checked={selectedIds.has(e.id)} onCheckedChange={() => toggleSelect(e.id)} />
                          </TableCell>
                        )}
                        <TableCell className="text-sm whitespace-nowrap py-4">
                          {e.date ? format(parseLocalDate(e.date), "MMM dd, yyyy") : "-"}
                        </TableCell>
                        <TableCell className="py-4">
                          <span className="font-semibold text-sm">{e.description || "N/A"}</span>
                          {e.transaction_type && <p className="text-xs text-muted-foreground mt-0.5">{e.transaction_type}</p>}
                        </TableCell>
                        <TableCell className="py-4">
                          <Badge variant="outline" className={`font-bold text-[10px] uppercase tracking-wider border-0 shadow-sm ${badgeClass}`}>
                            {badgeLabel}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right py-4">
                          <span className={`text-sm font-mono ${isDebit ? "font-medium" : "text-emerald-600 font-bold"}`}>
                            {isDebit ? "" : "-"}${amount.toFixed(2)}
                          </span>
                        </TableCell>
                        <TableCell className="text-right py-4">
                          <span className="text-sm font-mono font-bold">${e._runningBalance.toFixed(2)}</span>
                        </TableCell>
                        {canEdit && (
                          <TableCell className="py-4 text-right pr-6">
                            <div className="flex justify-end items-center gap-1">
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button variant="ghost" size="icon" className="w-8 h-8 text-muted-foreground hover:text-primary hover:bg-primary/10" onClick={() => handleEdit(e)}>
                                    <Pencil className="w-4 h-4" />
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent>Edit Entry</TooltipContent>
                              </Tooltip>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button variant="ghost" size="icon" className="w-8 h-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10" onClick={() => setDeleteEntry(e)}>
                                    <Trash2 className="w-4 h-4" />
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent>Delete Entry</TooltipContent>
                              </Tooltip>
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button variant="ghost" size="icon" className="w-8 h-8 text-muted-foreground hover:text-foreground">
                                    <MoreHorizontal className="w-4 h-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuItem onClick={() => handleRefund(e)} className="gap-2">
                                    <RotateCcw className="w-3.5 h-3.5" /> Refund Transaction
                                  </DropdownMenuItem>
                                  {e.transaction_type !== "Prepayment" && (
                                    <DropdownMenuItem onClick={() => handleConvertToPrepayment(e)} className="gap-2">
                                      <CreditCard className="w-3.5 h-3.5" /> Convert to Prepayment
                                    </DropdownMenuItem>
                                  )}
                                  <DropdownMenuItem onClick={() => handleArchiveEntry(e, true)} className="gap-2">
                                    <Archive className="w-3.5 h-3.5" /> Archive (Previous Owner)
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </div>
                          </TableCell>
                        )}
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </TooltipProvider>
        </CardContent>
      </Card>

      {/* Transaction Form */}
      {canEdit && formOpen && (
        <UnitLedgerTransactionForm
          open={formOpen}
          onOpenChange={(o) => { setFormOpen(o); if (!o) setEditingEntry(null); }}
          unitId={unitId}
          associationId={unitData?.associations?.id || associationId}
          onSuccess={() => { fetchLedger(true); setEditingEntry(null); }}
          editEntry={editingEntry}
        />
      )}

      {/* Invoice Dialog */}
      {canEdit && (
        <UnitLedgerInvoiceDialog
          open={invoiceOpen}
          onOpenChange={setInvoiceOpen}
          unitId={unitId}
          associationId={unitData?.associations?.id || associationId || ""}
          unitData={unitData}
          owners={owners}
          onSuccess={() => fetchLedger(true)}
        />
      )}

      {/* Bulk Delete Dialog */}

      {/* Bulk Change Type Dialog */}
      <Dialog open={bulkTypeOpen} onOpenChange={setBulkTypeOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Replace className="w-5 h-5 text-primary" /> Change Transaction Type
            </DialogTitle>
            <DialogDescription>
              Update the transaction type for {selectedIds.size} selected ledger {selectedIds.size === 1 ? "entry" : "entries"}.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <Label htmlFor="bulk-type-select">New Transaction Type</Label>
            <Select value={bulkNewType} onValueChange={setBulkNewType}>
              <SelectTrigger id="bulk-type-select">
                <SelectValue placeholder="Select a type..." />
              </SelectTrigger>
              <SelectContent>
                {TRANSACTION_TYPES.map((t) => (
                  <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setBulkTypeOpen(false)} disabled={bulkUpdating}>Cancel</Button>
            <Button onClick={handleBulkChangeType} disabled={!bulkNewType || bulkUpdating} className="gap-2">
              {bulkUpdating && <Loader2 className="w-4 h-4 animate-spin" />}
              Update {selectedIds.size} {selectedIds.size === 1 ? "Entry" : "Entries"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Bulk Delete Dialog */}
      <AlertDialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="text-destructive flex items-center gap-2">
              <AlertCircle className="w-6 h-6" /> Delete {selectedIds.size} Entries
            </AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete {selectedIds.size} selected ledger entries? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter className="mt-4">
            <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction disabled={isDeleting} onClick={handleBulkDelete} className="bg-destructive hover:bg-destructive/90 text-destructive-foreground">
              {isDeleting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Ban className="w-4 h-4 mr-2" />} Delete All Selected
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Single Delete Dialog */}
      <AlertDialog open={!!deleteEntry} onOpenChange={(o) => !o && setDeleteEntry(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="text-destructive flex items-center gap-2">
              <AlertCircle className="w-6 h-6" /> Delete Ledger Entry
            </AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete this entry? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          {deleteEntry && (
            <div className="bg-muted border rounded-lg p-3 text-sm mt-2">
              <div className="flex justify-between"><span className="text-muted-foreground">Date:</span><span className="font-medium">{format(parseLocalDate(deleteEntry.date), "MMM dd, yyyy")}</span></div>
              <div className="flex justify-between mt-1"><span className="text-muted-foreground">Amount:</span><span className="font-medium">${(Number(deleteEntry.debit || 0) || Number(deleteEntry.credit || 0)).toFixed(2)}</span></div>
              <div className="flex justify-between mt-1"><span className="text-muted-foreground">Type:</span><span className="font-medium capitalize">{Number(deleteEntry.debit || 0) > 0 ? "Charge" : "Payment"}</span></div>
            </div>
          )}
          <AlertDialogFooter className="mt-4">
            <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction disabled={isDeleting} onClick={handleDelete} className="bg-destructive hover:bg-destructive/90 text-destructive-foreground">
              {isDeleting ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Ban className="w-4 h-4 mr-2" />} Confirm Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
