import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Users, Plus, Search, MoreHorizontal, Edit, Trash2, Check, Archive, ArchiveRestore, ShieldCheck, Mail, Copy } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import RecordImportButton from "@/components/RecordImportButton";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import VendorCoaMappings from "@/components/vendors/VendorCoaMappings";
import { BulkVendorEditDialog } from "@/components/vendors/BulkVendorEditDialog";

const emptyForm = { name: "", contact_name: "", email: "", phone: "", address: "", tax_id: "", payment_terms: "30", notes: "", association_id: "", association_ids: [] as string[], is_active: true, is_1099_eligible: false, share_with_board: false, contract_end_date: "", insurance_carrier: "", insurance_policy_number: "", insurance_expiration_date: "" };

// Insurance status: active if expiration date is today or later
function getInsuranceStatus(v: any) {
  if (!v?.insurance_expiration_date) return { has: false, active: false };
  const exp = new Date(v.insurance_expiration_date + "T00:00:00");
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return {
    has: true,
    active: exp >= today,
    label: exp.toLocaleDateString(),
  };
}

// Returns: { label, isExpiring, isExpired }
function getContractEndStatus(date?: string | null) {
  if (!date) return null;
  const end = new Date(date + "T00:00:00");
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const diffDays = Math.floor((end.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  return {
    label: end.toLocaleDateString(),
    isExpired: diffDays < 0,
    isExpiring: diffDays >= 0 && diffDays <= 90,
    diffDays,
  };
}

export default function VendorsPage() {
  const { toast } = useToast();
  const [vendors, setVendors] = useState<any[]>([]);
  const [associations, setAssociations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [showArchived, setShowArchived] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form, setForm] = useState(emptyForm);
  const [bulkOpen, setBulkOpen] = useState(false);
  const [bulkText, setBulkText] = useState("");
  const [bulkSaving, setBulkSaving] = useState(false);
  const [bulkEditOpen, setBulkEditOpen] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const [vRes, aRes] = await Promise.all([
      supabase.from("vendors").select("*, associations(name)").order("name"),
      supabase.from("associations").select("id, name").eq("status", "active").order("name"),
    ]);
    setVendors(vRes.data || []);
    setAssociations(aRes.data || []);
    setLoading(false);
  };

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

  const filtered = vendors
    .filter(v => showArchived ? !v.is_active : v.is_active)
    .filter(v => v.name.toLowerCase().includes(search.toLowerCase()) || (v.contact_name || "").toLowerCase().includes(search.toLowerCase()));

  const archiveVendor = async (id: string, archive: boolean) => {
    const { error } = await supabase.from("vendors").update({ is_active: !archive }).eq("id", id);
    if (error) {
      toast({ variant: "destructive", title: "Error", description: error.message });
      return;
    }
    toast({ title: archive ? "Vendor archived" : "Vendor restored" });
    fetchData();
  };

  const openNew = () => {
    setEditing(null);
    const first = associations[0]?.id || "";
    setForm({ ...emptyForm, association_id: first, association_ids: first ? [first] : [] });
    setDialogOpen(true);
  };

  const openEdit = (v: any) => {
    setEditing(v);
    const ids: string[] = Array.isArray(v.association_ids) && v.association_ids.length > 0
      ? v.association_ids
      : (v.association_id ? [v.association_id] : []);
    setForm({
      name: v.name, contact_name: v.contact_name || "", email: v.email || "",
      phone: v.phone || "", address: v.address || "", tax_id: v.tax_id || "",
      payment_terms: v.payment_terms || "30", notes: v.notes || "",
      association_id: v.association_id || ids[0] || "",
      association_ids: ids,
      is_active: v.is_active,
      is_1099_eligible: v.is_1099_eligible || false,
      share_with_board: v.share_with_board || false,
      contract_end_date: v.contract_end_date || "",
      insurance_carrier: v.insurance_carrier || "",
      insurance_policy_number: v.insurance_policy_number || "",
      insurance_expiration_date: v.insurance_expiration_date || "",
    });
    setDialogOpen(true);
  };

  const toggleAssoc = (id: string, checked: boolean) => {
    setForm((prev) => {
      const set = new Set(prev.association_ids);
      if (checked) set.add(id); else set.delete(id);
      const next = Array.from(set);
      const primary = prev.association_id && set.has(prev.association_id) ? prev.association_id : (next[0] || "");
      return { ...prev, association_ids: next, association_id: primary };
    });
  };

  const handleSave = async () => {
    if (!form.name || form.association_ids.length === 0) {
      toast({ variant: "destructive", title: "Name and at least one association are required" });
      return;
    }
    const primary = form.association_ids.includes(form.association_id) ? form.association_id : form.association_ids[0];
    const payload = { ...form, association_id: primary, contract_end_date: form.contract_end_date || null, insurance_expiration_date: form.insurance_expiration_date || null, insurance_carrier: form.insurance_carrier || null, insurance_policy_number: form.insurance_policy_number || null };
    if (editing) {
      await supabase.from("vendors").update(payload as any).eq("id", editing.id);
      toast({ title: "Vendor updated" });
    } else {
      await supabase.from("vendors").insert(payload as any);
      toast({ title: "Vendor created" });
    }
    setDialogOpen(false);
    fetchData();
  };

  const sendInsuranceRequest = async (v: any) => {
    if (!v.email) {
      toast({ variant: "destructive", title: "No email on file", description: "Add a vendor email before sending an insurance request." });
      return;
    }
    const { data, error } = await supabase.functions.invoke("send-vendor-insurance-request", {
      body: { vendor_id: v.id },
    });
    if (error) {
      toast({ variant: "destructive", title: "Could not send request", description: error.message });
      return;
    }
    if (data?.ok) {
      toast({ title: "Insurance request sent", description: `Email delivered to ${data.sent_to}.` });
    } else if (data?.link) {
      try { await navigator.clipboard.writeText(data.link); } catch {}
      toast({ title: "Email failed — link copied", description: "Share the copied link manually with the vendor." });
    } else {
      toast({ variant: "destructive", title: "Could not send request", description: data?.error || "Unknown error" });
    }
  };

  const sendProfileRequest = async (v: any) => {
    if (!v.email) {
      toast({ variant: "destructive", title: "No email on file", description: "Add a vendor email before sending a profile request." });
      return;
    }
    const { data, error } = await supabase.functions.invoke("send-vendor-profile-request", {
      body: { vendor_id: v.id },
    });
    if (error) {
      toast({ variant: "destructive", title: "Could not send request", description: error.message });
      return;
    }
    if (data?.ok) {
      toast({ title: "Profile request sent", description: `Email delivered to ${data.sent_to}.` });
    } else if (data?.link) {
      try { await navigator.clipboard.writeText(data.link); } catch {}
      toast({ title: "Email failed — link copied", description: "Share the copied link manually with the vendor." });
    } else {
      toast({ variant: "destructive", title: "Could not send request", description: data?.error || "Unknown error" });
    }
  };

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

  const openBulk = () => {
    // Pre-populate with current vendors as: Vendor Name | address (single-line, \n becomes \\n for editing)
    const tsv = vendors
      .filter(v => v.is_active)
      .map(v => `${v.name}\t${(v.address || "").replace(/\r?\n/g, " \\n ")}`)
      .join("\n");
    setBulkText(tsv);
    setBulkOpen(true);
  };

  const handleBulkSave = async () => {
    setBulkSaving(true);
    try {
      const lines = bulkText.split("\n").map(l => l.trim()).filter(Boolean);
      const updates: { name: string; address: string }[] = [];
      for (const line of lines) {
        // Split on tab OR pipe — convert literal "\n" sequences back to real newlines
        const parts = line.includes("\t") ? line.split("\t") : line.split("|");
        if (parts.length < 2) continue;
        const name = parts[0].trim();
        const address = parts.slice(1).join(parts.includes("\t") ? "\t" : "|").trim().replace(/\s*\\n\s*/g, "\n");
        if (!name) continue;
        updates.push({ name, address });
      }

      const nameToId = new Map(vendors.map(v => [v.name.toLowerCase(), v.id]));
      let updated = 0;
      let skipped = 0;
      for (const u of updates) {
        const id = nameToId.get(u.name.toLowerCase());
        if (!id) { skipped++; continue; }
        const { error } = await supabase.from("vendors").update({ address: u.address || null }).eq("id", id);
        if (error) { skipped++; continue; }
        updated++;
      }
      toast({ title: `Bulk update complete`, description: `Updated ${updated}${skipped ? `, skipped ${skipped}` : ""}.` });
      setBulkOpen(false);
      fetchData();
    } finally {
      setBulkSaving(false);
    }
  };


  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"><Users className="h-6 w-6 text-primary" /> Vendors</h1>
          <p className="text-sm text-muted-foreground mt-1">Manage vendors, suppliers, and account mappings.</p>
        </div>
      </div>

      <Tabs defaultValue="vendors" className="space-y-4">
        <TabsList>
          <TabsTrigger value="vendors">Vendor List</TabsTrigger>
          <TabsTrigger value="mappings">Account Mappings</TabsTrigger>
        </TabsList>

        <TabsContent value="vendors" className="space-y-4">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="relative max-w-md w-full">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input placeholder="Search vendors..." className="pl-10" value={search} onChange={(e) => setSearch(e.target.value)} />
            </div>
            <div className="flex gap-2">
              <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>
              <RecordImportButton
                title="Import Vendors"
                description="Upload a CSV or Excel file with vendor records."
                expectedColumns={[
                  { key: "name", label: "Name", required: true },
                  { key: "contact_name", label: "Contact Name" },
                  { key: "email", label: "Email" },
                  { key: "phone", label: "Phone" },
                  { key: "address", label: "Address" },
                  { key: "tax_id", label: "Tax ID" },
                ]}
                onImport={async (rows) => {
                  const assocId = associations[0]?.id;
                  if (!assocId) throw new Error("Create an association first");
                  const payload = rows.map(r => ({
                    name: r.name || "Unknown",
                    contact_name: r.contact_name || null,
                    email: r.email || null,
                    phone: r.phone || null,
                    address: r.address || null,
                    tax_id: r.tax_id || null,
                    association_id: assocId,
                  }));
                  const { error } = await supabase.from("vendors").insert(payload);
                  if (error) throw error;
                  toast({ title: `Imported ${rows.length} vendors` });
                  fetchData();
                }}
                templateFileName="vendors_template.xlsx"
              />
              <Button variant="outline" className="gap-2" onClick={openBulk}><Edit className="h-4 w-4" /> Bulk Addresses</Button>
              <Button variant="outline" className="gap-2" onClick={() => setBulkEditOpen(true)}><Edit className="h-4 w-4" /> Bulk Edit</Button>
              <Button className="gap-2" onClick={openNew}><Plus className="h-4 w-4" /> Add Vendor</Button>
            </div>
          </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 vendors found.</CardContent></Card>
          ) : (
            <Card>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Vendor Name</TableHead>
                    <TableHead>Contact</TableHead>
                    <TableHead>Email</TableHead>
                    <TableHead>Phone</TableHead>
                    <TableHead>Terms</TableHead>
                    <TableHead>1099</TableHead>
                    <TableHead>Association</TableHead>
                    <TableHead>Contract End</TableHead>
                    <TableHead>Insurance</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="w-12" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filtered.map((v) => (
                    <TableRow key={v.id}>
                      <TableCell className="font-medium">
                        <a
                          href={`/dashboard/vendors/${v.id}`}
                          className="text-primary hover:underline"
                          onClick={(e) => { e.preventDefault(); window.location.assign(`/dashboard/vendors/${v.id}`); }}
                        >
                          {v.name}
                        </a>
                      </TableCell>
                      <TableCell>{v.contact_name || "—"}</TableCell>
                      <TableCell>{v.email || "—"}</TableCell>
                      <TableCell>{v.phone || "—"}</TableCell>
                      <TableCell>Net {v.payment_terms}</TableCell>
                      <TableCell>
                        <Checkbox
                          checked={v.is_1099_eligible}
                          onCheckedChange={async (checked) => {
                            await supabase.from("vendors").update({ is_1099_eligible: !!checked }).eq("id", v.id);
                            fetchData();
                          }}
                        />
                      </TableCell>
                      <TableCell className="max-w-[220px]">
                        {(() => {
                          const ids: string[] = Array.isArray(v.association_ids) && v.association_ids.length > 0
                            ? v.association_ids
                            : (v.association_id ? [v.association_id] : []);
                          const names = ids.map((id) => associations.find(a => a.id === id)?.name).filter(Boolean) as string[];
                          if (names.length === 0) return v.associations?.name || "—";
                          if (names.length === 1) return names[0];
                          return (
                            <span title={names.join(", ")}>
                              {names[0]} <Badge variant="outline" className="ml-1">+{names.length - 1}</Badge>
                            </span>
                          );
                        })()}
                      </TableCell>
                      <TableCell>
                        {(() => {
                          const status = getContractEndStatus(v.contract_end_date);
                          if (!status) return <span className="text-muted-foreground">—</span>;
                          const cls = status.isExpired
                            ? "text-destructive font-semibold"
                            : status.isExpiring
                              ? "text-destructive font-semibold"
                              : "";
                          const tip = status.isExpired
                            ? `Expired ${Math.abs(status.diffDays)} day${Math.abs(status.diffDays) === 1 ? "" : "s"} ago`
                            : status.isExpiring
                              ? `Expires in ${status.diffDays} day${status.diffDays === 1 ? "" : "s"}`
                              : undefined;
                          return <span className={cls} title={tip}>{status.label}</span>;
                        })()}
                      </TableCell>
                      <TableCell>
                        {(() => {
                          const ins = getInsuranceStatus(v);
                          if (!ins.has) {
                            return (
                              <Button variant="outline" size="sm" className="h-7 gap-1 text-xs" onClick={() => sendInsuranceRequest(v)}>
                                <Mail className="h-3 w-3" /> Request
                              </Button>
                            );
                          }
                          return ins.active ? (
                            <span className="inline-flex items-center gap-1 text-emerald-600" title={`Expires ${ins.label}`}>
                              <Check className="h-4 w-4" /> <span className="text-xs">{ins.label}</span>
                            </span>
                          ) : (
                            <span className="text-destructive font-semibold text-xs" title="Expired">Expired ({ins.label})</span>
                          );
                        })()}
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap items-center gap-1">
                          <Badge variant="outline" className={v.is_active ? "bg-emerald-100 text-emerald-700" : "bg-muted text-muted-foreground"}>
                            {v.is_active ? "Active" : "Inactive"}
                          </Badge>
                          {v.share_with_board && (
                            <Badge variant="outline" className="bg-blue-100 text-blue-700 border-blue-200">Shared with board</Badge>
                          )}
                        </div>
                      </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={() => openEdit(v)}><Edit className="h-4 w-4 mr-2" /> Edit</DropdownMenuItem>
                            <DropdownMenuItem onClick={() => sendInsuranceRequest(v)}><Mail className="h-4 w-4 mr-2" /> Request Insurance Info</DropdownMenuItem>
                            <DropdownMenuItem onClick={() => sendProfileRequest(v)}><Mail className="h-4 w-4 mr-2" /> Request Vendor Profile</DropdownMenuItem>
                            {v.is_active ? (
                              <DropdownMenuItem onClick={() => archiveVendor(v.id, true)}><Archive className="h-4 w-4 mr-2" /> Archive</DropdownMenuItem>
                            ) : (
                              <DropdownMenuItem onClick={() => archiveVendor(v.id, false)}><ArchiveRestore className="h-4 w-4 mr-2" /> Restore</DropdownMenuItem>
                            )}
                            <DropdownMenuItem className="text-destructive" onClick={() => handleDelete(v.id)}><Trash2 className="h-4 w-4 mr-2" /> Delete</DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="mappings">
          <VendorCoaMappings />
        </TabsContent>
      </Tabs>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader><DialogTitle>{editing ? "Edit" : "Add"} Vendor</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Associations</Label>
              <p className="text-xs text-muted-foreground mb-2">Select all associations this vendor serves.</p>
              <div className="max-h-48 overflow-y-auto rounded-md border border-border bg-background p-2 space-y-1">
                {associations.length === 0 ? (
                  <p className="text-sm text-muted-foreground p-2">No associations available.</p>
                ) : associations.map(a => {
                  const checked = form.association_ids.includes(a.id);
                  const isPrimary = form.association_id === a.id;
                  return (
                    <label key={a.id} className="flex items-center gap-2 px-2 py-1.5 rounded hover:bg-accent cursor-pointer">
                      <Checkbox checked={checked} onCheckedChange={(c) => toggleAssoc(a.id, !!c)} />
                      <span className="flex-1 text-sm">{a.name}</span>
                      {checked && (
                        isPrimary ? (
                          <Badge variant="outline" className="text-xs">Primary</Badge>
                        ) : (
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="h-6 text-xs"
                            onClick={(e) => { e.preventDefault(); setForm({ ...form, association_id: a.id }); }}
                          >
                            Make primary
                          </Button>
                        )
                      )}
                    </label>
                  );
                })}
              </div>
            </div>
            <div><Label>Vendor Name</Label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
            <div className="grid grid-cols-2 gap-4">
              <div><Label>Contact Name</Label><Input value={form.contact_name} onChange={(e) => setForm({ ...form, contact_name: e.target.value })} /></div>
              <div><Label>Phone</Label><Input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} /></div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div><Label>Email</Label><Input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></div>
              <div><Label>Payment Terms (days)</Label><Input value={form.payment_terms} onChange={(e) => setForm({ ...form, payment_terms: e.target.value })} /></div>
            </div>
            <div>
              <Label>Address</Label>
              <Textarea
                value={form.address}
                onChange={(e) => setForm({ ...form, address: e.target.value })}
                rows={3}
                placeholder={"Street\nCity, State ZIP"}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div><Label>Tax ID / EIN</Label><Input value={form.tax_id} onChange={(e) => setForm({ ...form, tax_id: e.target.value })} /></div>
              <div>
                <Label>Contract End Date</Label>
                <Input
                  type="date"
                  value={form.contract_end_date}
                  onChange={(e) => setForm({ ...form, contract_end_date: e.target.value })}
                />
              </div>
            </div>
            <div className="border-t pt-3">
              <Label className="text-sm font-semibold">Insurance</Label>
              <div className="grid grid-cols-2 gap-4 mt-2">
                <div><Label className="text-xs">Carrier</Label><Input value={form.insurance_carrier} onChange={(e) => setForm({ ...form, insurance_carrier: e.target.value })} /></div>
                <div><Label className="text-xs">Policy Number</Label><Input value={form.insurance_policy_number} onChange={(e) => setForm({ ...form, insurance_policy_number: e.target.value })} /></div>
              </div>
              <div className="mt-2">
                <Label className="text-xs">Expiration Date</Label>
                <Input type="date" value={form.insurance_expiration_date} onChange={(e) => setForm({ ...form, insurance_expiration_date: e.target.value })} />
              </div>
              {editing?.email && !form.insurance_expiration_date && (
                <p className="text-xs text-muted-foreground mt-2">Tip: Save first, then use "Request Insurance Info" from the row menu to email the vendor a submission link.</p>
              )}
            </div>
            <div className="flex items-center gap-2">
              <Checkbox
                id="is_1099_eligible"
                checked={form.is_1099_eligible}
                onCheckedChange={(checked) => setForm({ ...form, is_1099_eligible: !!checked })}
              />
              <Label htmlFor="is_1099_eligible">1099 Eligible</Label>
            </div>
            <div className="flex items-center gap-2">
              <Checkbox
                id="share_with_board"
                checked={form.share_with_board}
                onCheckedChange={(checked) => setForm({ ...form, share_with_board: !!checked })}
              />
              <Label htmlFor="share_with_board">Share contact info with board members (shows in the directory)</Label>
            </div>
            <div><Label>Notes</Label><Textarea value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} rows={2} /></div>
          </div>
          <DialogFooter><Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button></DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={bulkOpen} onOpenChange={setBulkOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader><DialogTitle>Bulk Update Vendor Addresses</DialogTitle></DialogHeader>
          <div className="space-y-3">
            <p className="text-sm text-muted-foreground">
              One vendor per line. Use a tab or pipe (<code>|</code>) between the vendor name and the address.
              Use <code>\n</code> within an address to insert a line break (e.g. <code>123 Main St \n Suite 200 \n Anytown, ST 00000</code>).
              Vendor names must match exactly (case-insensitive). Unmatched names are skipped.
            </p>
            <Textarea
              value={bulkText}
              onChange={(e) => setBulkText(e.target.value)}
              rows={16}
              className="font-mono text-xs"
              placeholder={"Acme Plumbing\t123 Main St \\n Suite 5 \\n Phoenix, AZ 85001\nBlueSky HVAC|PO Box 42 \\n Tempe, AZ 85281"}
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setBulkOpen(false)} disabled={bulkSaving}>Cancel</Button>
            <Button onClick={handleBulkSave} disabled={bulkSaving}>{bulkSaving ? "Saving..." : "Apply Updates"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <BulkVendorEditDialog
        open={bulkEditOpen}
        onOpenChange={setBulkEditOpen}
        vendors={vendors}
        onSaved={fetchData}
      />
    </div>
  );
}
