import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Loader2 } from "lucide-react";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  associationId?: string | null;
  onCreated: (vendor: { id: string; name: string; association_id: string; association_ids: string[] }) => void;
  defaultName?: string;
}

export default function QuickAddVendorDialog({ open, onOpenChange, associationId, onCreated, defaultName = "" }: Props) {
  const { toast } = useToast();
  const [saving, setSaving] = useState(false);
  const [associations, setAssociations] = useState<any[]>([]);
  const [form, setForm] = useState({
    name: defaultName,
    contact_name: "",
    email: "",
    phone: "",
    address: "",
    tax_id: "",
    payment_terms: "30",
    is_1099_eligible: false,
    notes: "",
    association_id: associationId || "",
  });

  useEffect(() => {
    if (open) {
      setForm((f) => ({ ...f, name: defaultName, association_id: associationId || f.association_id }));
      supabase.from("associations").select("id, name").order("name").then(({ data }) => setAssociations(data || []));
    }
  }, [open, associationId, defaultName]);

  const handleSave = async () => {
    if (!form.name.trim()) {
      toast({ variant: "destructive", title: "Name required" });
      return;
    }
    if (!form.association_id) {
      toast({ variant: "destructive", title: "Association required" });
      return;
    }
    setSaving(true);
    const payload = {
      name: form.name.trim(),
      contact_name: form.contact_name.trim() || null,
      email: form.email.trim() || null,
      phone: form.phone.trim() || null,
      address: form.address.trim() || null,
      tax_id: form.tax_id.trim() || null,
      payment_terms: form.payment_terms || "30",
      is_1099_eligible: form.is_1099_eligible,
      notes: form.notes.trim() || null,
      association_id: form.association_id,
      association_ids: [form.association_id],
      is_active: true,
    };
    const { data, error } = await supabase.from("vendors").insert(payload).select("id, name, association_id, association_ids").single();
    setSaving(false);
    if (error || !data) {
      toast({ variant: "destructive", title: "Failed to create vendor", description: error?.message });
      return;
    }
    toast({ title: "Vendor created", description: data.name });
    onCreated(data as any);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Add New Vendor</DialogTitle>
          <DialogDescription>Quickly create a vendor without leaving the invoice dialog.</DialogDescription>
        </DialogHeader>
        <div className="space-y-3">
          <div>
            <Label>Association *</Label>
            <select
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              value={form.association_id}
              onChange={(e) => setForm({ ...form, association_id: e.target.value })}
            >
              <option value="">Select association</option>
              {associations.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
            </select>
          </div>
          <div>
            <Label>Vendor Name *</Label>
            <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} autoFocus />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div><Label>Contact Name</Label><Input value={form.contact_name} onChange={(e) => setForm({ ...form, contact_name: e.target.value })} /></div>
            <div><Label>Email</Label><Input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></div>
            <div><Label>Phone</Label><Input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} /></div>
            <div><Label>Tax ID</Label><Input value={form.tax_id} onChange={(e) => setForm({ ...form, tax_id: e.target.value })} /></div>
          </div>
          <div>
            <Label>Address</Label>
            <Textarea rows={2} value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
          </div>
          <div className="grid grid-cols-2 gap-3 items-end">
            <div><Label>Payment Terms (days)</Label><Input value={form.payment_terms} onChange={(e) => setForm({ ...form, payment_terms: e.target.value })} /></div>
            <div className="flex items-center gap-2 pb-2">
              <Checkbox id="qv-1099" checked={form.is_1099_eligible} onCheckedChange={(v) => setForm({ ...form, is_1099_eligible: v === true })} />
              <Label htmlFor="qv-1099" className="font-normal cursor-pointer">1099 eligible</Label>
            </div>
          </div>
          <div>
            <Label>Notes</Label>
            <Textarea rows={2} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>Cancel</Button>
          <Button onClick={handleSave} disabled={saving}>
            {saving && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
            Create Vendor
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
