import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { ArrowLeftRight, Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } 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 { 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";

export default function TransfersPage() {
  const { toast } = useToast();
  const [transfers, setTransfers] = useState<any[]>([]);
  const [bankAccounts, setBankAccounts] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [form, setForm] = useState({
    from_bank_account_id: "", to_bank_account_id: "", amount: "",
    transfer_date: new Date().toISOString().split("T")[0], description: "", association_id: ""
  });

  const fetchData = async () => {
    setLoading(true);
    const [tRes, baRes, aRes] = await Promise.all([
      supabase.from("bank_transfers").select("*, from_account:bank_accounts!bank_transfers_from_bank_account_id_fkey(account_name), to_account:bank_accounts!bank_transfers_to_bank_account_id_fkey(account_name), associations(name)").order("transfer_date", { ascending: false }),
      supabase.from("bank_accounts").select("id, account_name, association_id").eq("status", "active").order("account_name"),
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
    ]);
    setTransfers(tRes.data || []);
    setBankAccounts(baRes.data || []);
    setAssociations(aRes.data || []);
    setLoading(false);
  };

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

  const handleCreate = async () => {
    if (!form.from_bank_account_id || !form.to_bank_account_id || !form.amount || !form.association_id) {
      toast({ variant: "destructive", title: "All fields are required" });
      return;
    }
    if (form.from_bank_account_id === form.to_bank_account_id) {
      toast({ variant: "destructive", title: "Cannot transfer to the same account" });
      return;
    }
    const amount = parseFloat(form.amount);
    const desc = form.description || "Bank Transfer";
    const fromAcct = bankAccounts.find(a => a.id === form.from_bank_account_id);
    const toAcct = bankAccounts.find(a => a.id === form.to_bank_account_id);

    // Create bank register entries for both accounts
    const [fromTxn, toTxn] = await Promise.all([
      supabase.from("bank_transactions").insert({
        bank_account_id: form.from_bank_account_id,
        association_id: form.association_id,
        date: form.transfer_date,
        transaction_type: "transfer_out",
        description: `Transfer to ${toAcct?.account_name || "account"}: ${desc}`,
        debit: 0, credit: amount,
      }).select("id").single(),
      supabase.from("bank_transactions").insert({
        bank_account_id: form.to_bank_account_id,
        association_id: form.association_id,
        date: form.transfer_date,
        transaction_type: "transfer_in",
        description: `Transfer from ${fromAcct?.account_name || "account"}: ${desc}`,
        debit: amount, credit: 0,
      }).select("id").single(),
    ]);

    // Create the transfer record
    await supabase.from("bank_transfers").insert({
      from_bank_account_id: form.from_bank_account_id,
      to_bank_account_id: form.to_bank_account_id,
      amount, transfer_date: form.transfer_date, description: desc,
      association_id: form.association_id,
      from_transaction_id: fromTxn.data?.id || null,
      to_transaction_id: toTxn.data?.id || null,
    });

    toast({ title: "Transfer completed" });
    setDialogOpen(false);
    fetchData();
  };

  const filteredAccounts = bankAccounts.filter(a => !form.association_id || a.association_id === form.association_id);

  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" /> Bank Transfers</h1>
          <p className="text-sm text-muted-foreground mt-1">Transfer funds between bank accounts.</p>
        </div>
        <Button className="gap-2" onClick={() => {
          setForm({ from_bank_account_id: "", to_bank_account_id: "", amount: "", transfer_date: new Date().toISOString().split("T")[0], description: "", association_id: associations[0]?.id || "" });
          setDialogOpen(true);
        }}><Plus className="h-4 w-4" /> New Transfer</Button>
      </div>

      {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>
      ) : transfers.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">No transfers recorded.</CardContent></Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>From Account</TableHead>
                <TableHead>To Account</TableHead>
                <TableHead>Description</TableHead>
                <TableHead>Association</TableHead>
                <TableHead className="text-right">Amount</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {transfers.map((t) => (
                <TableRow key={t.id}>
                  <TableCell className="font-medium">{t.transfer_date}</TableCell>
                  <TableCell>{t.from_account?.account_name || "—"}</TableCell>
                  <TableCell>{t.to_account?.account_name || "—"}</TableCell>
                  <TableCell>{t.description || "—"}</TableCell>
                  <TableCell>{t.associations?.name || "—"}</TableCell>
                  <TableCell className="text-right font-mono font-medium">${Number(t.amount).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>New Transfer</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Association</Label>
              <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v, from_bank_account_id: "", to_bank_account_id: "" })}>
                <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                <SelectContent>{associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>From Account</Label>
                <Select value={form.from_bank_account_id} onValueChange={(v) => setForm({ ...form, from_bank_account_id: v })}>
                  <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                  <SelectContent>{filteredAccounts.map(a => <SelectItem key={a.id} value={a.id}>{a.account_name}</SelectItem>)}</SelectContent>
                </Select>
              </div>
              <div>
                <Label>To Account</Label>
                <Select value={form.to_bank_account_id} onValueChange={(v) => setForm({ ...form, to_bank_account_id: v })}>
                  <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                  <SelectContent>{filteredAccounts.filter(a => a.id !== form.from_bank_account_id).map(a => <SelectItem key={a.id} value={a.id}>{a.account_name}</SelectItem>)}</SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div><Label>Amount</Label><Input type="number" value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })} placeholder="0.00" /></div>
              <div><Label>Date</Label><Input type="date" value={form.transfer_date} onChange={(e) => setForm({ ...form, transfer_date: e.target.value })} /></div>
            </div>
            <div><Label>Description</Label><Input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="e.g. Monthly reserve transfer" /></div>
          </div>
          <DialogFooter><Button onClick={handleCreate}>Transfer Funds</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
