import { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { format, parseISO } from "date-fns";
import {
  ArrowUpDown, ChevronUp, ChevronDown, Search, Loader2, AlertCircle,
  FileText, ChevronLeft, ChevronRight, RefreshCw, Upload
} 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 { useToast } from "@/hooks/use-toast";

interface Props {
  unitId: string;
}

export default function UnitTransactionHistory({ unitId }: Props) {
  const [entries, setEntries] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [syncing, setSyncing] = useState<null | "pull" | "push">(null);
  const { toast } = useToast();
  const navigate = useNavigate();

  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [sortConfig, setSortConfig] = useState({ key: "date", direction: "desc" as "asc" | "desc" });
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

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

  const fetchEntries = async () => {
    setLoading(true);
    setError(null);
    try {
      // Transaction History shows the FULL record — including entries from archived (moved-out) owners.
      const { data, error: fetchError } = await supabase
        .from("owner_ledger_entries")
        .select("*, owners(status, first_name, last_name)")
        .eq("unit_id", unitId)
        .order("date", { ascending: true })
        .order("created_at", { ascending: true });

      if (fetchError) throw fetchError;

      // Calculate running balance
      let balance = 0;
      const withBalance = (data || []).map((e) => {
        balance += Number(e.debit || 0) - Number(e.credit || 0);
        return { ...e, running_balance: balance };
      });

      setEntries(withBalance);
    } catch (err: any) {
      console.error("Error fetching entries:", err);
      setError("Unable to load transaction history. Please try again later.");
    } finally {
      setLoading(false);
    }
  };

  const handleBuildiumSync = async (mode: "pull" | "push") => {
    setSyncing(mode);
    try {
      if (mode === "pull") {
        // Pull is review-first: stage ledger entries and navigate to the review queue.
        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 fetchEntries();
      }
    } 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 {
      setSyncing(null);
    }
  };

  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 (startDate) result = result.filter((e) => e.date >= startDate);
    if (endDate) result = result.filter((e) => e.date <= endDate);
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      result = result.filter((e) => (e.description || "").toLowerCase().includes(q) || (e.transaction_type || "").toLowerCase().includes(q));
    }
    result.sort((a, b) => {
      let vA = a[sortConfig.key] ?? "";
      let vB = b[sortConfig.key] ?? "";
      if (vA < vB) return sortConfig.direction === "asc" ? -1 : 1;
      if (vA > vB) return sortConfig.direction === "asc" ? 1 : -1;
      return 0;
    });
    return result;
  }, [entries, startDate, endDate, 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 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" />;
  };

  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 transaction history...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-24 text-destructive">
        <AlertCircle className="w-10 h-10 mb-4" />
        <p className="font-medium">{error}</p>
        <Button variant="outline" className="mt-4" onClick={fetchEntries}>Try Again</Button>
      </div>
    );
  }

  return (
    <div className="py-4">
      <Card className="shadow-md border">
        <CardHeader className="bg-muted/50 border-b pb-6">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <CardTitle className="text-2xl flex items-center gap-2">
                <FileText className="w-6 h-6 text-primary" />
                Transaction History
              </CardTitle>
              <CardDescription className="mt-1">
                View and filter all historical ledger entries.
              </CardDescription>
            </div>
            <div className="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center flex-wrap">
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleBuildiumSync("pull")}
                  disabled={syncing !== null}
                  title="Pull this unit's ledger from Buildium"
                >
                  {syncing === "pull" ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-1" />}
                  Pull from Buildium
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleBuildiumSync("push")}
                  disabled={syncing !== null}
                  title="Push this unit's local ledger entries to Buildium"
                >
                  {syncing === "push" ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Upload className="w-4 h-4 mr-1" />}
                  Push to Buildium
                </Button>
              </div>
              <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 descriptions..." value={searchQuery} onChange={(e) => { setSearchQuery(e.target.value); setCurrentPage(1); }} className="pl-9 w-full sm:w-[200px]" />
              </div>
              <div className="flex items-center gap-2">
                <Input type="date" value={startDate} onChange={(e) => { setStartDate(e.target.value); setCurrentPage(1); }} className="w-full sm:w-[140px] text-sm" title="Start Date" />
                <span className="text-muted-foreground">-</span>
                <Input type="date" value={endDate} onChange={(e) => { setEndDate(e.target.value); setCurrentPage(1); }} className="w-full sm:w-[140px] text-sm" title="End Date" />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-muted/50">
                <TableRow>
                  <TableHead className="py-4 px-6">
                    <Button variant="ghost" onClick={() => handleSort("date")} className="hover:bg-muted -ml-4 h-8 flex items-center text-xs uppercase tracking-wider font-semibold">
                      Date <SortIcon columnKey="date" />
                    </Button>
                  </TableHead>
                  <TableHead className="py-4 px-6">
                    <Button variant="ghost" onClick={() => handleSort("description")} className="hover:bg-muted -ml-4 h-8 flex items-center text-xs uppercase tracking-wider font-semibold">
                      Description <SortIcon columnKey="description" />
                    </Button>
                  </TableHead>
                  <TableHead className="py-4 px-6 font-semibold text-xs uppercase tracking-wider">Type</TableHead>
                  <TableHead className="py-4 px-6 font-semibold text-right text-xs uppercase tracking-wider">Amount</TableHead>
                  <TableHead className="py-4 px-6 font-semibold text-right text-xs uppercase tracking-wider">Balance After</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paginatedData.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="h-48 text-center text-muted-foreground">
                      No transactions found matching your criteria.
                    </TableCell>
                  </TableRow>
                ) : (
                  paginatedData.map((e) => {
                    const isDebit = Number(e.debit || 0) > 0;
                    const amount = isDebit ? Number(e.debit) : Number(e.credit);

                    return (
                      <TableRow key={e.id} className="hover:bg-muted/30 transition-colors border-b">
                        <TableCell className="py-4 px-6 whitespace-nowrap text-sm">
                          {e.date ? format(parseISO(e.date), "MMM d, yyyy") : "-"}
                        </TableCell>
                        <TableCell className="py-4 px-6">
                          <div className="font-medium text-sm flex items-center gap-2 flex-wrap">
                            {e.description || "N/A"}
                            {e.owners?.status === "archived" && (
                              <Badge variant="outline" className="text-[10px] py-0 px-1.5 bg-muted text-muted-foreground border-muted-foreground/30">
                                Archived Owner
                              </Badge>
                            )}
                            {e.is_archived && (
                              <Badge variant="outline" className="text-[10px] py-0 px-1.5 bg-amber-50 text-amber-700 border-amber-300">
                                Archived
                              </Badge>
                            )}
                          </div>
                          <div className="text-xs text-muted-foreground mt-0.5 flex items-center gap-1.5">
                            {e.transaction_type && <span>{e.transaction_type}</span>}
                            {e.owners && (e.owners.first_name || e.owners.last_name) && (
                              <span className="opacity-70">• {e.owners.first_name} {e.owners.last_name}</span>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="py-4 px-6">
                          <Badge variant="outline" className={`font-normal ${isDebit ? "bg-destructive/10 text-destructive" : "bg-emerald-50 text-emerald-700"}`}>
                            {isDebit ? "Charge" : "Payment"}
                          </Badge>
                        </TableCell>
                        <TableCell className={`py-4 px-6 text-right font-semibold ${isDebit ? "text-foreground" : "text-emerald-600"}`}>
                          {isDebit ? "+" : "-"}${amount.toFixed(2)}
                        </TableCell>
                        <TableCell className="py-4 px-6 text-right font-medium">
                          ${(e.running_balance || 0).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>
  );
}
