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

type Threshold = { id?: string; min_amount: number; max_amount: number | null; required_approvals: number };
type VendorEx = { id?: string; vendor_name: string; required_approvals: number };

export default function BillApprovalRulesPage() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState<any[]>([]);
  const [associationId, setAssociationId] = useState<string>("");
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  const [ruleId, setRuleId] = useState<string | null>(null);
  const [enabled, setEnabled] = useState(true);
  const [requiredApprovals, setRequiredApprovals] = useState(2);
  const [thresholds, setThresholds] = useState<Threshold[]>([]);
  const [vendorExceptions, setVendorExceptions] = useState<VendorEx[]>([]);

  useEffect(() => {
    supabase.from("associations").select("id,name").eq("status", "active").order("name")
      .then(({ data }) => setAssociations(data || []));
  }, []);

  useEffect(() => {
    if (!associationId) return;
    setLoading(true);
    (async () => {
      const { data: rule } = await supabase.from("bill_approval_rules")
        .select("*").eq("association_id", associationId).maybeSingle();
      if (rule) {
        setRuleId(rule.id);
        setEnabled(rule.enabled);
        setRequiredApprovals(rule.required_approvals);
        const [{ data: th }, { data: ve }] = await Promise.all([
          supabase.from("bill_approval_rule_thresholds").select("*").eq("rule_id", rule.id).order("min_amount"),
          supabase.from("bill_approval_rule_vendor_exceptions").select("*").eq("rule_id", rule.id).order("vendor_name"),
        ]);
        setThresholds(th || []);
        setVendorExceptions(ve || []);
      } else {
        setRuleId(null);
        setEnabled(true);
        setRequiredApprovals(2);
        setThresholds([]);
        setVendorExceptions([]);
      }
      setLoading(false);
    })();
  }, [associationId]);

  const save = async () => {
    if (!associationId) return;
    setSaving(true);
    try {
      let id = ruleId;
      if (id) {
        const { error } = await supabase.from("bill_approval_rules")
          .update({ enabled, required_approvals: requiredApprovals }).eq("id", id);
        if (error) throw error;
      } else {
        const { data, error } = await supabase.from("bill_approval_rules")
          .insert({ association_id: associationId, enabled, required_approvals: requiredApprovals })
          .select().single();
        if (error) throw error;
        id = data.id;
        setRuleId(id);
      }

      // Replace thresholds
      await supabase.from("bill_approval_rule_thresholds").delete().eq("rule_id", id);
      if (thresholds.length) {
        const { error } = await supabase.from("bill_approval_rule_thresholds").insert(
          thresholds.map(t => ({ rule_id: id, min_amount: t.min_amount, max_amount: t.max_amount, required_approvals: t.required_approvals }))
        );
        if (error) throw error;
      }

      // Replace vendor exceptions
      await supabase.from("bill_approval_rule_vendor_exceptions").delete().eq("rule_id", id);
      if (vendorExceptions.length) {
        const { error } = await supabase.from("bill_approval_rule_vendor_exceptions").insert(
          vendorExceptions.filter(v => v.vendor_name.trim())
            .map(v => ({ rule_id: id, vendor_name: v.vendor_name.trim(), required_approvals: v.required_approvals }))
        );
        if (error) throw error;
      }
      toast({ title: "Saved", description: "Approval rules updated." });
    } catch (e: any) {
      toast({ title: "Save failed", description: e.message, variant: "destructive" });
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Bill Approval Rules</h1>
        <p className="text-sm text-muted-foreground">
          Configure how many board approvals are required to mark a bill as approved.
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Association</CardTitle>
        </CardHeader>
        <CardContent>
          <Select value={associationId} onValueChange={setAssociationId}>
            <SelectTrigger className="max-w-md"><SelectValue placeholder="Select an association" /></SelectTrigger>
            <SelectContent>
              {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
            </SelectContent>
          </Select>
        </CardContent>
      </Card>

      {associationId && (
        loading ? (
          <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin" /></div>
        ) : (
          <>
            <Card>
              <CardHeader><CardTitle>Default Rule</CardTitle></CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center gap-3">
                  <Switch checked={enabled} onCheckedChange={setEnabled} id="enabled" />
                  <Label htmlFor="enabled">Enable approval rules for this association</Label>
                </div>
                <div className="max-w-xs space-y-2">
                  <Label>Default # of approvals required</Label>
                  <Input type="number" min={0} value={requiredApprovals}
                    onChange={(e) => setRequiredApprovals(parseInt(e.target.value) || 0)} />
                  <p className="text-xs text-muted-foreground">
                    A bill becomes "approved" once this many board members approve it.
                  </p>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  Amount Thresholds
                  <Button size="sm" variant="outline" onClick={() => setThresholds([...thresholds, { min_amount: 0, max_amount: null, required_approvals: 2 }])}>
                    <Plus className="h-4 w-4 mr-1" /> Add
                  </Button>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {thresholds.length === 0 ? (
                  <p className="text-sm text-muted-foreground">No thresholds. Default rule applies to all amounts.</p>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Min Amount ($)</TableHead>
                        <TableHead>Max Amount ($, blank = no max)</TableHead>
                        <TableHead># Approvals</TableHead>
                        <TableHead className="w-12"></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {thresholds.map((t, i) => (
                        <TableRow key={i}>
                          <TableCell>
                            <Input type="number" step="0.01" value={t.min_amount}
                              onChange={(e) => { const c = [...thresholds]; c[i].min_amount = parseFloat(e.target.value) || 0; setThresholds(c); }} />
                          </TableCell>
                          <TableCell>
                            <Input type="number" step="0.01" value={t.max_amount ?? ""}
                              onChange={(e) => { const c = [...thresholds]; c[i].max_amount = e.target.value === "" ? null : parseFloat(e.target.value); setThresholds(c); }} />
                          </TableCell>
                          <TableCell>
                            <Input type="number" min={0} value={t.required_approvals}
                              onChange={(e) => { const c = [...thresholds]; c[i].required_approvals = parseInt(e.target.value) || 0; setThresholds(c); }} />
                          </TableCell>
                          <TableCell>
                            <Button size="icon" variant="ghost" onClick={() => setThresholds(thresholds.filter((_, x) => x !== i))}>
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
                <p className="text-xs text-muted-foreground mt-3">
                  When a bill's amount falls into a range, that row's # of approvals is used instead of the default.
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  Vendor Exceptions
                  <Button size="sm" variant="outline" onClick={() => setVendorExceptions([...vendorExceptions, { vendor_name: "", required_approvals: 1 }])}>
                    <Plus className="h-4 w-4 mr-1" /> Add
                  </Button>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {vendorExceptions.length === 0 ? (
                  <p className="text-sm text-muted-foreground">No vendor exceptions.</p>
                ) : (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Vendor Name (exact match, case-insensitive)</TableHead>
                        <TableHead># Approvals</TableHead>
                        <TableHead className="w-12"></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {vendorExceptions.map((v, i) => (
                        <TableRow key={i}>
                          <TableCell>
                            <Input value={v.vendor_name}
                              onChange={(e) => { const c = [...vendorExceptions]; c[i].vendor_name = e.target.value; setVendorExceptions(c); }} />
                          </TableCell>
                          <TableCell>
                            <Input type="number" min={0} value={v.required_approvals}
                              onChange={(e) => { const c = [...vendorExceptions]; c[i].required_approvals = parseInt(e.target.value) || 0; setVendorExceptions(c); }} />
                          </TableCell>
                          <TableCell>
                            <Button size="icon" variant="ghost" onClick={() => setVendorExceptions(vendorExceptions.filter((_, x) => x !== i))}>
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                )}
                <p className="text-xs text-muted-foreground mt-3">
                  Vendor exceptions take priority over thresholds and the default rule.
                </p>
              </CardContent>
            </Card>

            <div className="flex justify-end">
              <Button onClick={save} disabled={saving}>
                {saving ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Save className="h-4 w-4 mr-2" />}
                Save Rules
              </Button>
            </div>
          </>
        )
      )}
    </div>
  );
}
