import { useState, useEffect, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { ArrowLeftRight, Plus, CheckCircle2, Circle, Save } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
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 { formatDateEST } from "@/lib/timezoneUtils";

export default function ReconciliationsPage() {
  const { toast } = useToast();
  const [bankAccounts, setBankAccounts] = useState<any[]>([]);
  const [transactions, setTransactions] = useState<any[]>([]);
  const [reconciliations, setReconciliations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // Reconciliation state
  const [selectedAccountId, setSelectedAccountId] = useState("");
  const [isReconciling, setIsReconciling] = useState(false);
  const [statementDate, setStatementDate] = useState(new Date().toISOString().split("T")[0]);
  const [openingBalance, setOpeningBalance] = useState("0");
  const [closingBalance, setClosingBalance] = useState("");
  const [localCleared, setLocalCleared] = useState<Set<string>>(new Set());
  const [dialogOpen, setDialogOpen] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const [baRes, recRes] = await Promise.all([
      supabase.from("bank_accounts").select("*, associations(name)").eq("status", "active").order("account_name"),
      supabase.from("bank_reconciliations").select("*, bank_accounts(account_name)").order("statement_date", { ascending: false }).limit(20),
    ]);
    setBankAccounts(baRes.data || []);
    setReconciliations(recRes.data || []);
    setLoading(false);
  };

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

  const startReconciliation = async () => {
    if (!selectedAccountId || !closingBalance) {
      toast({ variant: "destructive", title: "Select an account and enter closing balance" });
      return;
    }
    // Fetch uncleared transactions
    const { data } = await supabase
      .from("bank_transactions")
      .select("*")
      .eq("bank_account_id", selectedAccountId)
      .eq("is_cleared", false)
      .order("date");
    setTransactions(data || []);
    setLocalCleared(new Set());
    setIsReconciling(true);
    setDialogOpen(false);
  };

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

  const clearedTotal = useMemo(() => {
    return transactions
      .filter(t => localCleared.has(t.id))
      .reduce((s, t) => s + Number(t.debit) - Number(t.credit), 0);
  }, [transactions, localCleared]);

  const adjustedBalance = parseFloat(openingBalance) + clearedTotal;
  const difference = parseFloat(closingBalance || "0") - adjustedBalance;

  const finishReconciliation = async () => {
    if (Math.abs(difference) > 0.01) {
      toast({ variant: "destructive", title: "Reconciliation does not balance", description: `Difference: $${difference.toFixed(2)}` });
      return;
    }
    const acct = bankAccounts.find(a => a.id === selectedAccountId);

    // Mark transactions as cleared
    const ids = Array.from(localCleared);
    if (ids.length) {
      await supabase.from("bank_transactions").update({ is_cleared: true, cleared_date: statementDate }).in("id", ids);
    }

    // Create reconciliation record
    await supabase.from("bank_reconciliations").insert({
      bank_account_id: selectedAccountId,
      association_id: acct?.association_id,
      statement_date: statementDate,
      opening_balance: parseFloat(openingBalance),
      closing_balance: parseFloat(closingBalance),
      cleared_balance: adjustedBalance,
      difference: 0,
      status: "completed",
      reconciled_at: new Date().toISOString(),
    });

    toast({ title: "Reconciliation completed!" });
    setIsReconciling(false);
    fetchData();
  };

  if (isReconciling) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
              <ArrowLeftRight className="h-6 w-6 text-primary" /> Bank Reconciliation
            </h1>
            <p className="text-sm text-muted-foreground">
              {bankAccounts.find(a => a.id === selectedAccountId)?.account_name} — Statement date: {statementDate}
            </p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => setIsReconciling(false)}>Cancel</Button>
            <Button onClick={finishReconciliation} disabled={Math.abs(difference) > 0.01} className="gap-2">
              <Save className="h-4 w-4" /> Finish Reconciliation
            </Button>
          </div>
        </div>

        {/* Summary */}
        <div className="grid gap-4 md:grid-cols-4">
          <Card>
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground uppercase font-semibold">Statement Closing</p>
              <p className="text-2xl font-bold font-mono">${parseFloat(closingBalance || "0").toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground uppercase font-semibold">Cleared Balance</p>
              <p className="text-2xl font-bold font-mono">${adjustedBalance.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground uppercase font-semibold">Items Cleared</p>
              <p className="text-2xl font-bold">{localCleared.size} / {transactions.length}</p>
            </CardContent>
          </Card>
          <Card className={Math.abs(difference) < 0.01 ? "border-emerald-500" : "border-destructive"}>
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground uppercase font-semibold">Difference</p>
              <p className={`text-2xl font-bold font-mono ${Math.abs(difference) < 0.01 ? "text-emerald-600" : "text-destructive"}`}>
                ${Math.abs(difference).toLocaleString("en-US", { minimumFractionDigits: 2 })}
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Transactions to reconcile */}
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-10">✓</TableHead>
                <TableHead>Date</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Description</TableHead>
                <TableHead>Ref #</TableHead>
                <TableHead className="text-right">Debit</TableHead>
                <TableHead className="text-right">Credit</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {transactions.length === 0 ? (
                <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">All transactions are cleared.</TableCell></TableRow>
              ) : transactions.map((t) => (
                <TableRow key={t.id} className={localCleared.has(t.id) ? "bg-emerald-50/50" : ""}>
                  <TableCell>
                    <button onClick={() => toggleItem(t.id)} className="hover:opacity-70">
                      {localCleared.has(t.id)
                        ? <CheckCircle2 className="h-4 w-4 text-emerald-600" />
                        : <Circle className="h-4 w-4 text-muted-foreground" />}
                    </button>
                  </TableCell>
                  <TableCell className="whitespace-nowrap">{formatDateEST(t.date)}</TableCell>
                  <TableCell><Badge variant="outline" className="text-xs capitalize">{t.transaction_type.replace("_", " ")}</Badge></TableCell>
                  <TableCell>{t.description || "—"}</TableCell>
                  <TableCell>{t.reference_number || "—"}</TableCell>
                  <TableCell className="text-right font-mono">{Number(t.debit) > 0 ? `$${Number(t.debit).toFixed(2)}` : "—"}</TableCell>
                  <TableCell className="text-right font-mono">{Number(t.credit) > 0 ? `$${Number(t.credit).toFixed(2)}` : "—"}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2"><ArrowLeftRight className="h-6 w-6 text-primary" /> Reconciliations</h1>
          <p className="text-sm text-muted-foreground mt-1">Reconcile bank statements with your records.</p>
        </div>
        <Button className="gap-2" onClick={() => setDialogOpen(true)}><Plus className="h-4 w-4" /> Start Reconciliation</Button>
      </div>

      {/* Past reconciliations */}
      {loading ? (
        <div className="flex justify-center py-12"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>
      ) : reconciliations.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">No reconciliations completed yet.</CardContent></Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Statement Date</TableHead>
                <TableHead>Bank Account</TableHead>
                <TableHead className="text-right">Opening Balance</TableHead>
                <TableHead className="text-right">Closing Balance</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Reconciled</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {reconciliations.map((r) => (
                <TableRow key={r.id}>
                  <TableCell className="font-medium">{r.statement_date}</TableCell>
                  <TableCell>{r.bank_accounts?.account_name || "—"}</TableCell>
                  <TableCell className="text-right font-mono">${Number(r.opening_balance).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                  <TableCell className="text-right font-mono">${Number(r.closing_balance).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                  <TableCell><Badge variant="outline" className={r.status === "completed" ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}>{r.status}</Badge></TableCell>
                  <TableCell>{r.reconciled_at ? formatDateEST(r.reconciled_at) : "—"}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      {/* Start reconciliation dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Start Bank Reconciliation</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Bank Account</Label>
              <Select value={selectedAccountId} onValueChange={setSelectedAccountId}>
                <SelectTrigger><SelectValue placeholder="Select account" /></SelectTrigger>
                <SelectContent>{bankAccounts.map(a => <SelectItem key={a.id} value={a.id}>{a.account_name} — {a.associations?.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div><Label>Statement Date</Label><Input type="date" value={statementDate} onChange={(e) => setStatementDate(e.target.value)} /></div>
            <div><Label>Statement Opening Balance</Label><Input type="number" value={openingBalance} onChange={(e) => setOpeningBalance(e.target.value)} placeholder="0.00" /></div>
            <div><Label>Statement Closing Balance</Label><Input type="number" value={closingBalance} onChange={(e) => setClosingBalance(e.target.value)} placeholder="0.00" /></div>
          </div>
          <DialogFooter><Button onClick={startReconciliation}>Begin Reconciliation</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
