import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Plus, Trash2, Save } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Input } from "@/components/ui/input";

interface Mapping {
  id?: string;
  association_id: string;
  vendor_id: string;
  chart_of_accounts_id: string;
  notes: string;
  isNew?: boolean;
}

export default function VendorCoaMappings() {
  const { toast } = useToast();
  const [mappings, setMappings] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [vendors, setVendors] = useState<any[]>([]);
  const [accounts, setAccounts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [newRow, setNewRow] = useState<Mapping | null>(null);
  const [filterAssociation, setFilterAssociation] = useState<string>("all");

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

  const fetchAll = async () => {
    setLoading(true);
    const [mRes, aRes, vRes, cRes] = await Promise.all([
      supabase.from("vendor_coa_mappings").select("*, associations(name), vendors(name), chart_of_accounts(id, account_number, account_name)").order("created_at", { ascending: false }),
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
      supabase.from("vendors").select("id, name").order("name"),
      supabase.from("chart_of_accounts").select("id, account_number, account_name").eq("is_active", true).order("account_number"),
    ]);
    setMappings(mRes.data || []);
    setAssociations(aRes.data || []);
    setVendors(vRes.data || []);
    setAccounts(cRes.data || []);
    setLoading(false);
  };

  const filtered = filterAssociation === "all"
    ? mappings
    : mappings.filter(m => m.association_id === filterAssociation);

  const handleAdd = () => {
    setNewRow({ association_id: "", vendor_id: "", chart_of_accounts_id: "", notes: "", isNew: true });
  };

  const handleSaveNew = async () => {
    if (!newRow || !newRow.association_id || !newRow.vendor_id || !newRow.chart_of_accounts_id) {
      toast({ variant: "destructive", title: "Association, vendor, and account are required" });
      return;
    }
    const { error } = await supabase.from("vendor_coa_mappings").insert({
      association_id: newRow.association_id,
      vendor_id: newRow.vendor_id,
      chart_of_accounts_id: newRow.chart_of_accounts_id,
      notes: newRow.notes || null,
    });
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message.includes("unique") ? "This association + vendor mapping already exists" : error.message });
      return;
    }
    toast({ title: "Mapping created" });
    setNewRow(null);
    fetchAll();
  };

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

  const handleUpdateAccount = async (id: string, chart_of_accounts_id: string) => {
    await supabase.from("vendor_coa_mappings").update({ chart_of_accounts_id }).eq("id", id);
    toast({ title: "Mapping updated" });
    fetchAll();
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
        <CardTitle className="text-lg">Vendor → Account Mappings</CardTitle>
        <div className="flex items-center gap-3">
          <Select value={filterAssociation} onValueChange={setFilterAssociation}>
            <SelectTrigger className="w-[200px]"><SelectValue placeholder="Filter by association" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Associations</SelectItem>
              {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
            </SelectContent>
          </Select>
          <Button size="sm" className="gap-1" onClick={handleAdd} disabled={!!newRow}>
            <Plus className="h-4 w-4" /> Add Mapping
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex justify-center py-8"><div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" /></div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Association</TableHead>
                <TableHead>Vendor</TableHead>
                <TableHead>Chart of Account</TableHead>
                <TableHead>Notes</TableHead>
                <TableHead className="w-20" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {newRow && (
                <TableRow className="bg-muted/30">
                  <TableCell>
                    <Select value={newRow.association_id} onValueChange={v => setNewRow({ ...newRow, association_id: v })}>
                      <SelectTrigger className="text-xs"><SelectValue placeholder="Select" /></SelectTrigger>
                      <SelectContent>{associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}</SelectContent>
                    </Select>
                  </TableCell>
                  <TableCell>
                    <Select value={newRow.vendor_id} onValueChange={v => setNewRow({ ...newRow, vendor_id: v })}>
                      <SelectTrigger className="text-xs"><SelectValue placeholder="Select" /></SelectTrigger>
                      <SelectContent>{vendors.map(v => <SelectItem key={v.id} value={v.id}>{v.name}</SelectItem>)}</SelectContent>
                    </Select>
                  </TableCell>
                  <TableCell>
                    <Select value={newRow.chart_of_accounts_id} onValueChange={v => setNewRow({ ...newRow, chart_of_accounts_id: v })}>
                      <SelectTrigger className="text-xs"><SelectValue placeholder="Select" /></SelectTrigger>
                      <SelectContent>{accounts.map(a => <SelectItem key={a.id} value={a.id}>{a.account_number} - {a.account_name}</SelectItem>)}</SelectContent>
                    </Select>
                  </TableCell>
                  <TableCell>
                    <Input className="text-xs" placeholder="Optional notes" value={newRow.notes} onChange={e => setNewRow({ ...newRow, notes: e.target.value })} />
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button size="icon" variant="ghost" className="h-7 w-7" onClick={handleSaveNew}><Save className="h-4 w-4 text-primary" /></Button>
                      <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => setNewRow(null)}><Trash2 className="h-4 w-4 text-muted-foreground" /></Button>
                    </div>
                  </TableCell>
                </TableRow>
              )}
              {filtered.length === 0 && !newRow ? (
                <TableRow><TableCell colSpan={5} className="text-center text-muted-foreground py-8">No mappings yet. Click "Add Mapping" to get started.</TableCell></TableRow>
              ) : filtered.map(m => (
                <TableRow key={m.id}>
                  <TableCell className="text-sm">{m.associations?.name || "—"}</TableCell>
                  <TableCell className="text-sm">{m.vendors?.name || "—"}</TableCell>
                  <TableCell>
                    <Select value={m.chart_of_accounts_id} onValueChange={v => handleUpdateAccount(m.id, v)}>
                      <SelectTrigger className="text-xs"><SelectValue /></SelectTrigger>
                      <SelectContent>{accounts.map(a => <SelectItem key={a.id} value={a.id}>{a.account_number} - {a.account_name}</SelectItem>)}</SelectContent>
                    </Select>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">{m.notes || "—"}</TableCell>
                  <TableCell>
                    <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => handleDelete(m.id)}><Trash2 className="h-4 w-4" /></Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </CardContent>
    </Card>
  );
}
