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 { 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";

const blankForm = {
  account_name: "",
  account_number: "",
  routing_number: "",
  bank_name: "",
  account_type: "checking",
  account_category: "operating",
  current_balance: "0",
  next_check_number: "1001",
  status: "active",
};

export default function CompanyBankAccountsPage() {
  const { toast } = useToast();
  const navigate = useNavigate();
  const [accounts, setAccounts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [showArchived, setShowArchived] = useState(false);
  const [form, setForm] = useState({ ...blankForm });

  const fetchData = async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("company_bank_accounts")
      .select("*")
      .order("account_name");
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
    } else {
      setAccounts(data || []);
    }
    setLoading(false);
  };

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

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

  const openNew = () => {
    setEditing(null);
    setForm({ ...blankForm });
    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",
      next_check_number: a.next_check_number?.toString() || "1001",
      status: a.status || "active",
    });
    setDialogOpen(true);
  };

  const handleSave = async () => {
    if (!form.account_name.trim()) {
      toast({ variant: "destructive", title: "Account name is required" });
      return;
    }
    const payload = {
      account_name: form.account_name.trim(),
      account_number: form.account_number || null,
      routing_number: form.routing_number || null,
      bank_name: form.bank_name || null,
      account_type: form.account_type,
      account_category: form.account_category,
      current_balance: parseFloat(form.current_balance) || 0,
      next_check_number: parseInt(form.next_check_number) || 1001,
      status: form.status,
    };
    const { error } = editing
      ? await supabase.from("company_bank_accounts").update(payload).eq("id", editing.id)
      : await supabase.from("company_bank_accounts").insert(payload);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
      return;
    }
    toast({ title: editing ? "Account updated" : "Account created" });
    setDialogOpen(false);
    fetchData();
  };

  const archive = async (id: string, archive: boolean) => {
    const { error } = await supabase
      .from("company_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 remove = async (id: string) => {
    if (!confirm("Permanently delete this account? Linked transactions will be unlinked.")) return;
    const { error } = await supabase.from("company_bank_accounts").delete().eq("id", id);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
      return;
    }
    toast({ title: "Account deleted" });
    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" /> Company Bank Accounts
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            Bank accounts for the management company's own books — separate from any client association.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={() => setShowArchived((s) => !s)}>
            {showArchived ? <ArchiveRestore className="h-4 w-4 mr-1" /> : <Archive className="h-4 w-4 mr-1" />}
            {showArchived ? "Show Active" : "Show Archived"}
          </Button>
          <Button className="gap-2" onClick={openNew}>
            <Plus className="h-4 w-4" /> Add Account
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Accounts</CardTitle>
          <CardDescription>{filtered.length} {showArchived ? "archived" : "active"} account(s)</CardDescription>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Account Name</TableHead>
                <TableHead>Bank</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Category</TableHead>
                <TableHead className="text-right">Balance</TableHead>
                <TableHead>Next Check #</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow><TableCell colSpan={8} className="text-center py-8 text-muted-foreground">Loading...</TableCell></TableRow>
              ) : filtered.length === 0 ? (
                <TableRow><TableCell colSpan={8} className="text-center py-8 text-muted-foreground">No accounts. Click "Add Account" to create one.</TableCell></TableRow>
              ) : filtered.map((a) => (
                <TableRow key={a.id}>
                  <TableCell className="font-medium">{a.account_name}</TableCell>
                  <TableCell>{a.bank_name || "—"}</TableCell>
                  <TableCell><Badge variant="outline" className="text-xs">{a.account_type}</Badge></TableCell>
                  <TableCell><Badge variant="secondary" className="text-xs">{a.account_category}</Badge></TableCell>
                  <TableCell className="text-right">${Number(a.current_balance || 0).toLocaleString("en-US", { minimumFractionDigits: 2 })}</TableCell>
                  <TableCell>{a.next_check_number}</TableCell>
                  <TableCell><Badge variant={a.status === "active" ? "default" : "secondary"} className="text-xs">{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/company-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 === "active" ? (
                          <DropdownMenuItem onClick={() => archive(a.id, true)}>
                            <Archive className="h-4 w-4 mr-2" /> Archive
                          </DropdownMenuItem>
                        ) : (
                          <DropdownMenuItem onClick={() => archive(a.id, false)}>
                            <ArchiveRestore className="h-4 w-4 mr-2" /> Restore
                          </DropdownMenuItem>
                        )}
                        <DropdownMenuItem className="text-destructive" onClick={() => remove(a.id)}>
                          <Trash2 className="h-4 w-4 mr-2" /> Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit" : "Add"} Company Bank Account</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4">
            <div>
              <Label>Account Name *</Label>
              <Input value={form.account_name} onChange={(e) => setForm({ ...form, account_name: e.target.value })} placeholder="e.g. Avria Operating Checking" />
            </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>
                    <SelectItem value="cd">CD</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Account Number</Label>
                <Input value={form.account_number} onChange={(e) => setForm({ ...form, account_number: e.target.value })} />
              </div>
              <div>
                <Label>Routing Number</Label>
                <Input value={form.routing_number} onChange={(e) => setForm({ ...form, routing_number: e.target.value })} />
              </div>
            </div>
            <div className="grid grid-cols-3 gap-4">
              <div>
                <Label>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="payroll">Payroll</SelectItem>
                    <SelectItem value="other">Other</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Current Balance</Label>
                <Input type="number" step="0.01" value={form.current_balance} onChange={(e) => setForm({ ...form, current_balance: e.target.value })} />
              </div>
              <div>
                <Label>Next Check #</Label>
                <Input type="number" value={form.next_check_number} onChange={(e) => setForm({ ...form, next_check_number: e.target.value })} />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
