import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { useNavigate } from "react-router-dom";
import { Landmark, Plus, MoreHorizontal, Edit, Trash2, Eye, Archive, ArchiveRestore } from "lucide-react";
import RecordImportButton from "@/components/RecordImportButton";
import { Button } from "@/components/ui/button";
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 { 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";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";

export default function BankAccountsPage() {
  const { toast } = useToast();
  const navigate = useNavigate();
  const [accounts, setAccounts] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [selectedAssocId, setSelectedAssocId] = useState("all");
  const [showArchived, setShowArchived] = useState(false);
  const [form, setForm] = useState({
    account_name: "", account_number: "", routing_number: "", bank_name: "",
    account_type: "checking", account_category: "operating", current_balance: "0",
    status: "active", association_id: ""
  });

  const fetchData = async () => {
    setLoading(true);
    const [acctRes, assocRes] = await Promise.all([
      supabase.from("bank_accounts").select("*, associations(name)").order("account_name"),
      supabase.from("associations").select("id, name, zoho_organization_id").eq("status", "active").order("name"),
    ]);
    setAccounts(acctRes.data || []);
    setAssociations(assocRes.data || []);
    setLoading(false);
  };

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

  const filtered = accounts
    .filter(a => showArchived ? a.status === "archived" : a.status !== "archived")
    .filter(a => selectedAssocId === "all" ? true : a.association_id === selectedAssocId);

  const archiveAccount = async (id: string, archive: boolean) => {
    const { error } = await supabase.from("bank_accounts").update({ status: archive ? "archived" : "active" }).eq("id", id);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
      return;
    }
    toast({ title: archive ? "Account archived" : "Account restored" });
    fetchData();
  };

  const openNew = () => {
    setEditing(null);
    setForm({
      account_name: "", account_number: "", routing_number: "", bank_name: "",
      account_type: "checking", account_category: "operating", current_balance: "0",
      status: "active", association_id: associations[0]?.id || ""
    });
    setDialogOpen(true);
  };

  const openEdit = (a: any) => {
    setEditing(a);
    setForm({
      account_name: a.account_name, account_number: a.account_number || "",
      routing_number: a.routing_number || "", bank_name: a.bank_name || "",
      account_type: a.account_type || "checking", account_category: a.account_category || "operating",
      current_balance: a.current_balance?.toString() || "0", status: a.status,
      association_id: a.association_id
    });
    setDialogOpen(true);
  };

  const handleSave = async () => {
    if (!form.account_name || !form.association_id) {
      toast({ variant: "destructive", title: "Account name and association are required" });
      return;
    }
    const payload = { ...form, current_balance: parseFloat(form.current_balance) || 0 };
    if (editing) {
      await supabase.from("bank_accounts").update(payload).eq("id", editing.id);
      toast({ title: "Account updated" });
    } else {
      await supabase.from("bank_accounts").insert(payload);
      toast({ title: "Account created" });
    }
    setDialogOpen(false);
    fetchData();
  };

  const handleDelete = async (id: string) => {
    await supabase.from("bank_accounts").delete().eq("id", id);
    toast({ title: "Account deleted" });
    fetchData();
  };

  const categoryTotals = filtered.reduce((acc: Record<string, number>, a) => {
    const cat = a.account_category || "operating";
    acc[cat] = (acc[cat] || 0) + Number(a.current_balance || 0);
    return acc;
  }, {});

  const totalBalance = filtered.reduce((s, a) => s + Number(a.current_balance || 0), 0);

  const categoryLabels: Record<string, string> = {
    operating: "Operating", reserve: "Reserve", special_assessment: "Special Assessment"
  };

  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" /> Bank Accounts
          </h1>
          <p className="text-sm text-muted-foreground mt-1">Manage association bank accounts and balances.</p>
        </div>
        <div className="flex gap-2">
          <Select value={selectedAssocId} onValueChange={setSelectedAssocId}>
            <SelectTrigger className="w-48"><SelectValue placeholder="All Associations" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Associations</SelectItem>
              {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
            </SelectContent>
          </Select>
          <RecordImportButton
            title="Import Bank Accounts"
            description="Upload a CSV or Excel file with bank account records."
            expectedColumns={[
              { key: "account_name", label: "Account Name", required: true },
              { key: "account_number", label: "Account Number" },
              { key: "bank_name", label: "Bank Name" },
              { key: "account_type", label: "Account Type" },
              { key: "account_category", label: "Category" },
              { key: "current_balance", label: "Current Balance" },
            ]}
            onImport={async (rows) => {
              const assocId = associations[0]?.id;
              if (!assocId) throw new Error("Create an association first");
              const payload = rows.map(r => ({
                account_name: r.account_name || "Unknown",
                account_number: r.account_number || null,
                bank_name: r.bank_name || null,
                account_type: r.account_type || "checking",
                account_category: r.account_category || "operating",
                current_balance: parseFloat(r.current_balance) || 0,
                association_id: assocId,
              }));
              const { error } = await supabase.from("bank_accounts").insert(payload);
              if (error) throw error;
              toast({ title: `Imported ${rows.length} bank accounts` });
              fetchData();
            }}
            templateFileName="bank_accounts_template.xlsx"
          />
          <Button variant="outline" className="gap-2" onClick={() => setShowArchived(s => !s)}>
            {showArchived ? <><ArchiveRestore className="h-4 w-4" /> Show Active</> : <><Archive className="h-4 w-4" /> Show Archived</>}
          </Button>
          <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> Add Account</Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="pt-6">
            <p className="text-sm text-muted-foreground">Total Balance</p>
            <p className="text-3xl font-bold text-foreground">${totalBalance.toLocaleString("en-US", { minimumFractionDigits: 2 })}</p>
          </CardContent>
        </Card>
        {Object.entries(categoryTotals).map(([cat, total]) => (
          <Card key={cat}>
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">{categoryLabels[cat] || cat}</p>
              <p className="text-2xl font-bold text-foreground">${(total as number).toLocaleString()}</p>
            </CardContent>
          </Card>
        ))}
      </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>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">No bank accounts found.</CardContent></Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Account Name</TableHead>
                <TableHead>Bank</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Account #</TableHead>
                <TableHead>Association</TableHead>
                <TableHead className="text-right">Balance</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((a) => (
                <TableRow key={a.id}>
                  <TableCell className="font-medium">{a.account_name}</TableCell>
                  <TableCell>{a.bank_name || "—"}</TableCell>
                  <TableCell className="capitalize">{a.account_type}</TableCell>
                  <TableCell>
                    <Badge variant="outline">{categoryLabels[a.account_category] || a.account_category}</Badge>
                  </TableCell>
                  <TableCell>{a.account_number ? `****${a.account_number.slice(-4)}` : "—"}</TableCell>
                  <TableCell>{a.associations?.name || "—"}</TableCell>
                  <TableCell className="text-right font-medium font-mono">
                    ${Number(a.current_balance).toLocaleString("en-US", {minimumFractionDigits: 2} as any)}
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" className={a.status === "active" ? "bg-emerald-100 text-emerald-700" : "bg-muted text-muted-foreground"}>
                      {a.status}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => navigate(`/dashboard/bank-register?account=${a.id}`)}>
                          <Eye className="h-4 w-4 mr-2" /> View Register
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => openEdit(a)}><Edit className="h-4 w-4 mr-2" /> Edit</DropdownMenuItem>
                        {a.status === "archived" ? (
                          <DropdownMenuItem onClick={() => archiveAccount(a.id, false)}><ArchiveRestore className="h-4 w-4 mr-2" /> Restore</DropdownMenuItem>
                        ) : (
                          <DropdownMenuItem onClick={() => archiveAccount(a.id, true)}><Archive className="h-4 w-4 mr-2" /> Archive</DropdownMenuItem>
                        )}
                        <DropdownMenuItem className="text-destructive" onClick={() => handleDelete(a.id)}>
                          <Trash2 className="h-4 w-4 mr-2" /> Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader><DialogTitle>{editing ? "Edit" : "Add"} Bank Account</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 association" /></SelectTrigger>
                <SelectContent>
                  {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Account Name</Label>
              <Input value={form.account_name} onChange={(e) => setForm({ ...form, account_name: e.target.value })} />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Bank Name</Label>
                <Input value={form.bank_name} onChange={(e) => setForm({ ...form, bank_name: e.target.value })} />
              </div>
              <div>
                <Label>Account Type</Label>
                <Select value={form.account_type} onValueChange={(v) => setForm({ ...form, account_type: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="checking">Checking</SelectItem>
                    <SelectItem value="savings">Savings</SelectItem>
                    <SelectItem value="money_market">Money Market</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div>
              <Label>Account Category</Label>
              <Select value={form.account_category} onValueChange={(v) => setForm({ ...form, account_category: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="operating">Operating</SelectItem>
                  <SelectItem value="reserve">Reserve</SelectItem>
                  <SelectItem value="special_assessment">Special Assessment</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div><Label>Account #</Label><Input value={form.account_number} onChange={(e) => setForm({ ...form, account_number: e.target.value })} /></div>
              <div><Label>Routing #</Label><Input value={form.routing_number} onChange={(e) => setForm({ ...form, routing_number: e.target.value })} /></div>
            </div>
            <div><Label>Opening Balance</Label><Input type="number" value={form.current_balance} onChange={(e) => setForm({ ...form, current_balance: e.target.value })} /></div>
          </div>
          <DialogFooter><Button onClick={handleSave}>{editing ? "Update" : "Create Account"}</Button></DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
