import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Landmark, Plus, Search, MoreHorizontal, Edit, CheckCircle, Eye } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";

export default function DepositBatchesPage() {
  const { toast } = useToast();
  const [batches, setBatches] = 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({
    bank_account_id: "", deposit_date: new Date().toISOString().split("T")[0],
    memo: "", association_id: ""
  });

  const fetchData = async () => {
    setLoading(true);
    const [bRes, baRes, aRes] = await Promise.all([
      supabase.from("deposit_batches").select("*, bank_accounts(account_name), associations(name)").order("deposit_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"),
    ]);
    setBatches(bRes.data || []);
    setBankAccounts(baRes.data || []);
    setAssociations(aRes.data || []);
    setLoading(false);
  };

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

  const handleCreate = async () => {
    if (!form.bank_account_id || !form.association_id) { toast({ variant: "destructive", title: "Bank account and association required" }); return; }
    await supabase.from("deposit_batches").insert({
      bank_account_id: form.bank_account_id,
      deposit_date: form.deposit_date,
      memo: form.memo || null,
      association_id: form.association_id,
    });
    toast({ title: "Deposit batch created" });
    setDialogOpen(false);
    fetchData();
  };

  const postBatch = async (batch: any) => {
    // Create bank transaction for the deposit
    const acct = bankAccounts.find(a => a.id === batch.bank_account_id);
    await supabase.from("bank_transactions").insert({
      bank_account_id: batch.bank_account_id,
      association_id: batch.association_id,
      date: batch.deposit_date,
      transaction_type: "deposit",
      description: `Deposit batch${batch.memo ? ` - ${batch.memo}` : ""}`,
      debit: batch.total_amount,
      credit: 0,
      related_entity_type: "deposit_batch",
      related_entity_id: batch.id,
    });
    await supabase.from("deposit_batches").update({ status: "posted" }).eq("id", batch.id);
    toast({ title: "Deposit posted to bank register" });
    fetchData();
  };

  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"><Landmark className="h-6 w-6 text-primary" /> Deposit Batches</h1>
          <p className="text-sm text-muted-foreground mt-1">Group owner payments into deposit batches.</p>
        </div>
        <Button className="gap-2" onClick={() => {
          setForm({ bank_account_id: bankAccounts[0]?.id || "", deposit_date: new Date().toISOString().split("T")[0], memo: "", association_id: associations[0]?.id || "" });
          setDialogOpen(true);
        }}><Plus className="h-4 w-4" /> New Deposit Batch</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>
      ) : batches.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">No deposit batches found.</CardContent></Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Deposit Date</TableHead>
                <TableHead>Bank Account</TableHead>
                <TableHead>Association</TableHead>
                <TableHead>Memo</TableHead>
                <TableHead className="text-right">Total</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {batches.map((b) => (
                <TableRow key={b.id}>
                  <TableCell className="font-medium">{b.deposit_date}</TableCell>
                  <TableCell>{b.bank_accounts?.account_name || "—"}</TableCell>
                  <TableCell>{b.associations?.name || "—"}</TableCell>
                  <TableCell>{b.memo || "—"}</TableCell>
                  <TableCell className="text-right font-mono font-medium">${Number(b.total_amount).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                  <TableCell>
                    <Badge variant="outline" className={b.status === "posted" ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}>{b.status}</Badge>
                  </TableCell>
                  <TableCell>
                    {b.status === "open" && (
                      <Button variant="ghost" size="sm" onClick={() => postBatch(b)} className="gap-1">
                        <CheckCircle className="h-4 w-4" /> Post
                      </Button>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>New Deposit Batch</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Association</Label>
              <Select value={form.association_id} onValueChange={(v) => setForm({ ...form, association_id: v })}>
                <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                <SelectContent>{associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div>
              <Label>Bank Account</Label>
              <Select value={form.bank_account_id} onValueChange={(v) => setForm({ ...form, bank_account_id: v })}>
                <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                <SelectContent>{bankAccounts.filter(a => !form.association_id || a.association_id === form.association_id).map(a => <SelectItem key={a.id} value={a.id}>{a.account_name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div><Label>Deposit Date</Label><Input type="date" value={form.deposit_date} onChange={(e) => setForm({ ...form, deposit_date: e.target.value })} /></div>
            <div><Label>Memo</Label><Input value={form.memo} onChange={(e) => setForm({ ...form, memo: e.target.value })} /></div>
          </div>
          <DialogFooter><Button onClick={handleCreate}>Create Batch</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
