import { useState, useEffect, useRef } from "react";
import { Mail, Printer, Settings, Users, Plus, Save, Loader2, Eye, Stamp, Trash2, Image, Type } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Checkbox } from "@/components/ui/checkbox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Textarea } from "@/components/ui/textarea";
import { useSavedFormTemplates } from "@/hooks/useSavedFormTemplates";
import LoadTemplateDialog from "@/components/LoadTemplateDialog";
import { supabase } from "@/integrations/supabase/client";
import { useAssociation } from "@/contexts/AssociationContext";
import { useToast } from "@/hooks/use-toast";

const ENVELOPE_SIZES = {
  "#10": { label: "#10 Standard (4⅛ × 9½ in)", width: "9.5in", height: "4.125in" },
  "#9": { label: "#9 Reply (3⅞ × 8⅞ in)", width: "8.875in", height: "3.875in" },
  "#6": { label: "#6¾ (3⅝ × 6½ in)", width: "6.5in", height: "3.625in" },
  "a7": { label: "A7 Invitation (5¼ × 7¼ in)", width: "7.25in", height: "5.25in" },
};

const STAMP_POSITIONS = {
  "top-right": { label: "Top Right", style: { top: "0.35in", right: "0.5in" } },
  "top-center": { label: "Top Center", style: { top: "0.35in", left: "50%", transform: "translateX(-50%)" } },
  "bottom-right": { label: "Bottom Right", style: { bottom: "0.35in", right: "0.5in" } },
  "bottom-left": { label: "Bottom Left", style: { bottom: "0.35in", left: "0.5in" } },
  "top-left-below": { label: "Below Return Address", style: { top: "1.6in", left: "0.5in" } },
};

const PRESET_STAMPS = [
  { id: "certified", label: "CERTIFIED MAIL", text: "CERTIFIED MAIL", style: { border: "2px solid #c00", color: "#c00", fontWeight: "bold", padding: "4px 12px", fontSize: "11px", letterSpacing: "2px", textTransform: "uppercase" } },
  { id: "priority", label: "PRIORITY", text: "PRIORITY", style: { background: "#1a56db", color: "#fff", fontWeight: "bold", padding: "4px 14px", fontSize: "11px", letterSpacing: "1px", borderRadius: "3px" } },
  { id: "confidential", label: "CONFIDENTIAL", text: "CONFIDENTIAL", style: { border: "1.5px solid #333", color: "#333", fontWeight: "bold", padding: "3px 10px", fontSize: "10px", letterSpacing: "2px" } },
  { id: "do-not-forward", label: "DO NOT FORWARD", text: "DO NOT FORWARD", style: { border: "2px solid #c00", color: "#c00", fontWeight: "bold", padding: "3px 10px", fontSize: "10px", letterSpacing: "1px" } },
  { id: "first-class", label: "FIRST CLASS MAIL", text: "FIRST CLASS MAIL", style: { background: "#166534", color: "#fff", fontWeight: "bold", padding: "4px 12px", fontSize: "10px", letterSpacing: "1px", borderRadius: "2px" } },
  { id: "return-service", label: "RETURN SERVICE REQUESTED", text: "RETURN SERVICE REQUESTED", style: { color: "#333", fontWeight: "bold", fontSize: "9px", letterSpacing: "1px", textTransform: "uppercase" } },
  { id: "address-service", label: "ADDRESS SERVICE REQUESTED", text: "ADDRESS SERVICE REQUESTED", style: { color: "#333", fontWeight: "bold", fontSize: "9px", letterSpacing: "1px", textTransform: "uppercase" } },
  { id: "official", label: "OFFICIAL BUSINESS", text: "OFFICIAL BUSINESS", style: { border: "1.5px solid #1e40af", color: "#1e40af", fontWeight: "bold", padding: "3px 10px", fontSize: "10px", letterSpacing: "1px" } },
];

export default function EnvelopePrintingForm() {
  const { toast } = useToast();
  const associationCtx = useAssociation() || {};
  const selectedAssociation = associationCtx.selectedAssociation || "";
  const [envelopeSize, setEnvelopeSize] = useState("#10");
  const [returnAddress, setReturnAddress] = useState("");
  const [printMode, setPrintMode] = useState("all-owners");
  const [customRecipientName, setCustomRecipientName] = useState("");
  const [customRecipientAddress, setCustomRecipientAddress] = useState("");
  const [includeBarcode, setIncludeBarcode] = useState(false);
  const [stamps, setStamps] = useState([]);

  const [associations, setAssociations] = useState([]);
  const [selectedAssoc, setSelectedAssoc] = useState(selectedAssociation || "");
  const [owners, setOwners] = useState([]);
  const [loadingOwners, setLoadingOwners] = useState(false);
  const [selectedOwnerIds, setSelectedOwnerIds] = useState(new Set());
  const [showPreview, setShowPreview] = useState(false);

  const templates = useSavedFormTemplates("envelope");
  const printRef = useRef(null);

  // Load associations
  useEffect(() => {
    (async () => {
      const { data } = await supabase.from("associations").select("id, name, address, city, state, zip, care_of_address, mailing_address").eq("status", "active").order("name");
      setAssociations(data || []);
    })();
  }, []);

  // Set return address from selected association
  useEffect(() => {
    if (!selectedAssoc || !associations.length) return;
    const assoc = associations.find(a => a.id === selectedAssoc);
    if (assoc) {
      const mailingAddr = assoc.mailing_address || assoc.care_of_address;
      const lines = [assoc.name];
      if (mailingAddr) lines.push(mailingAddr);
      else {
        if (assoc.address) lines.push(assoc.address);
        if (assoc.city || assoc.state || assoc.zip) {
          lines.push([assoc.city, assoc.state].filter(Boolean).join(", ") + (assoc.zip ? ` ${assoc.zip}` : ""));
        }
      }
      setReturnAddress(lines.join("\n"));
    }
  }, [selectedAssoc, associations]);

  // Load owners when association changes
  useEffect(() => {
    if (!selectedAssoc) {
      setOwners([]);
      setSelectedOwnerIds(new Set());
      setLoadingOwners(false);
      return;
    }

    let cancelled = false;
    const loadOwners = async () => {
      setLoadingOwners(true);
      try {
        const { data, error } = await supabase
          .from("owners")
          .select("id, first_name, last_name, mailing_address, property_address, alternate_address_1, alternate_address_2, street_address, unit_id, units(unit_number, address, city, state, zip)")
          .eq("association_id", selectedAssoc)
          .eq("status", "active")
          .order("last_name");

        if (error) throw error;

        if (!cancelled) {
          setOwners(data || []);
          setSelectedOwnerIds(new Set());
        }
      } catch (error) {
        console.error("Error loading owners:", error);
        if (!cancelled) {
          setOwners([]);
          setSelectedOwnerIds(new Set());
        }
      } finally {
        if (!cancelled) setLoadingOwners(false);
      }
    };

    loadOwners();
    return () => {
      cancelled = true;
    };
  }, [selectedAssoc]);

  // Sync with global association context
  useEffect(() => {
    if (selectedAssociation) setSelectedAssoc(selectedAssociation);
  }, [selectedAssociation]);


  const addStamp = (type = "text") => {
    setStamps(prev => [...prev, {
      id: Date.now(), type, text: type === "text" ? "CERTIFIED MAIL" : "", presetId: "", imageUrl: "",
      position: "top-right", customStyle: { fontSize: "11", color: "#cc0000", fontWeight: "bold", border: true, background: "" },
    }]);
  };
  const addPresetStamp = (presetId) => {
    const preset = PRESET_STAMPS.find(p => p.id === presetId);
    if (!preset) return;
    setStamps(prev => [...prev, { id: Date.now(), type: "preset", presetId, text: preset.text, imageUrl: "", position: "top-right", customStyle: {} }]);
  };
  const updateStamp = (id, field, value) => setStamps(prev => prev.map(s => s.id === id ? { ...s, [field]: value } : s));
  const updateStampStyle = (id, field, value) => setStamps(prev => prev.map(s => s.id === id ? { ...s, customStyle: { ...s.customStyle, [field]: value } } : s));
  const removeStamp = (id) => setStamps(prev => prev.filter(s => s.id !== id));

  const getStampInlineStyle = (stamp) => {
    if (stamp.type === "preset") return PRESET_STAMPS.find(p => p.id === stamp.presetId)?.style || {};
    if (stamp.type === "image") return {};
    const s = stamp.customStyle;
    return {
      fontSize: `${s.fontSize || 11}px`, color: s.color || "#000", fontWeight: s.fontWeight || "normal",
      ...(s.border ? { border: `1.5px solid ${s.color || "#000"}`, padding: "3px 10px" } : {}),
      ...(s.background ? { background: s.background, color: "#fff", padding: "4px 12px", borderRadius: "2px" } : {}),
      letterSpacing: "1px", fontFamily: "Arial, sans-serif", lineHeight: "1.4", whiteSpace: "pre-line",
    };
  };
  const renderStampHtml = (stamp) => {
    if (stamp.type === "image" && stamp.imageUrl) return `<img src="${stamp.imageUrl}" style="max-height:0.6in;max-width:2in;" />`;
    const style = getStampInlineStyle(stamp);
    const styleStr = Object.entries(style).map(([k, v]) => `${k.replace(/([A-Z])/g, '-$1').toLowerCase()}:${v}`).join(";");
    return `<span style="${styleStr}">${(stamp.text || "").replace(/\n/g, "<br>")}</span>`;
  };

  const getFormData = () => ({ envelopeSize, returnAddress, printMode, includeBarcode, selectedAssoc, stamps });
  const applyFormData = (d) => {
    if (d.envelopeSize) setEnvelopeSize(d.envelopeSize);
    if (d.returnAddress !== undefined) setReturnAddress(d.returnAddress);
    if (d.printMode) setPrintMode(d.printMode);
    if (d.includeBarcode !== undefined) setIncludeBarcode(d.includeBarcode);
    if (d.selectedAssoc) setSelectedAssoc(d.selectedAssoc);
    if (d.stamps) setStamps(d.stamps);
  };
  const handleSave = () => templates.saveTemplate(`Envelope - ${envelopeSize}`, getFormData());
  const handleLoad = async (id) => { const r = await templates.loadTemplate(id); if (r?.form_data) applyFormData(r.form_data); };
  const handleNew = () => { templates.newTemplate(); setEnvelopeSize("#10"); setReturnAddress(""); setPrintMode("all-owners"); setIncludeBarcode(false); };

  const toggleOwner = (id) => {
    setSelectedOwnerIds(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  const selectAll = () => setSelectedOwnerIds(new Set(owners.map(o => o.id)));
  const deselectAll = () => setSelectedOwnerIds(new Set());

  /**
   * Group owners by unit_id so co-owners on the same unit share one envelope.
   * Returns array of { names: string, owner: firstOwner } where names is combined.
   */
  const getGroupedRecipients = () => {
    if (printMode === "custom") {
      if (!customRecipientName.trim() && !customRecipientAddress.trim()) return [];
      return [{ combinedName: customRecipientName.trim() || "Recipient", owner: null, customAddress: customRecipientAddress.trim() }];
    }
    const pool = printMode === "selected" ? owners.filter(o => selectedOwnerIds.has(o.id)) : owners;
    const groups = new Map();
    let noUnitCounter = 0;

    for (const owner of pool) {
      const key = owner.unit_id || `__no_unit_${noUnitCounter++}`;
      const group = groups.get(key) || [];
      group.push(owner);
      groups.set(key, group);
    }

    return Array.from(groups.values()).map(group => {
      const names = [...new Set(group.map(o => `${o.first_name || ""} ${o.last_name || ""}`.trim()).filter(Boolean))];
      let combinedName = "Unknown Owner";
      if (names.length === 1) combinedName = names[0];
      else if (names.length === 2) combinedName = `${names[0]} & ${names[1]}`;
      else if (names.length > 2) combinedName = names.slice(0, -1).join(", ") + " & " + names[names.length - 1];

      return { combinedName, owner: group[0] };
    });
  };

  const formatAddressLines = (value) => {
    const lines = String(value || "")
      .replace(/\r\n/g, "\n")
      .replace(/\r/g, "\n")
      .split("\n")
      .map(line => line.trim())
      .filter(Boolean);

    if (lines.length > 1) {
      return {
        line1: lines[0],
        line2: lines.slice(1).join(", "),
      };
    }

    const singleLine = lines[0] || "";
    const commaParts = singleLine.split(",").map(part => part.trim()).filter(Boolean);

    if (commaParts.length === 2) {
      return { line1: commaParts[0], line2: commaParts[1] };
    }

    if (commaParts.length === 3) {
      return { line1: commaParts[0], line2: commaParts.slice(1).join(", ") };
    }

    return { line1: singleLine, line2: "" };
  };

  const extractZip = (text) => {
    const m = (text || "").match(/\b(\d{5}(?:-\d{4})?)\s*$/);
    return m ? m[1] : "";
  };

  const getOwnerAddress = (owner) => {
    const unit = Array.isArray(owner.units) ? owner.units[0] : owner.units;
    const unitAddress = unit?.address || [
      unit?.unit_number,
      [unit?.city, unit?.state].filter(Boolean).join(", ") + (unit?.zip ? ` ${unit.zip}` : ""),
    ].filter(Boolean).join("\n");
    const alternateAddress = [owner.alternate_address_1, owner.alternate_address_2].filter(Boolean).join("\n");
    const resolvedAddress = owner.mailing_address || alternateAddress || owner.property_address || owner.street_address || unitAddress || unit?.unit_number || "";
    const { line1, line2 } = formatAddressLines(resolvedAddress);
    const zip = unit?.zip || extractZip(line2) || extractZip(line1);

    return {
      name: `${owner.first_name || ""} ${owner.last_name || ""}`.trim(),
      line1,
      line2,
      zip,
    };
  };

  const handlePrint = () => {
    const grouped = getGroupedRecipients();
    if (!grouped.length) {
      toast({ variant: "destructive", title: "No recipients", description: printMode === "custom" ? "Enter a recipient name and address." : "Select an association and owners to print envelopes." });
      return;
    }
    setShowPreview(true);
    setTimeout(() => {
      if (printRef.current) {
        const printWindow = window.open("", "_blank");
        if (!printWindow) return;
        const size = ENVELOPE_SIZES[envelopeSize];
        const barcodeScript = includeBarcode ? `<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"><\/script>` : "";
        printWindow.document.write(`<!DOCTYPE html><html><head><title>Envelopes</title>
          ${barcodeScript}
          <style>
            @page { size: ${size.width} ${size.height}; margin: 0; }
            * { box-sizing: border-box; margin: 0; padding: 0; }
            body { font-family: Arial, sans-serif; }
            .envelope {
              width: ${size.width}; height: ${size.height};
              position: relative; page-break-after: always;
              padding: 0.4in;
            }
            .envelope:last-child { page-break-after: auto; }
            .return-address {
              position: absolute; top: 0.4in; left: 0.5in;
              font-size: 10px; line-height: 1.5; white-space: pre-line;
            }
            .recipient {
              position: absolute; top: 50%; left: 50%;
              transform: translate(-30%, -30%);
              font-size: 13px; line-height: 1.6; text-align: center;
            }
            .recipient .name { font-weight: 600; }
            .barcode-container {
              position: absolute; bottom: 0.25in; left: 0.5in; right: 0.5in;
              text-align: center;
            }
            .barcode-container svg { height: 0.5in; width: auto; }
          </style>
        </head><body>`);

        grouped.forEach(({ combinedName, owner, customAddress }, idx) => {
          let addr;
          if (customAddress !== undefined) {
            const { line1, line2 } = formatAddressLines(customAddress);
            const zip = extractZip(line2) || extractZip(line1);
            addr = { name: combinedName, line1, line2, zip };
          } else {
            addr = getOwnerAddress(owner);
          }
          const barcodeHtml = includeBarcode && addr.zip
            ? `<div class="barcode-container"><svg id="bc-${idx}"></svg></div>`
            : "";
          printWindow.document.write(`
            <div class="envelope">
              <div class="return-address">${returnAddress.replace(/\n/g, "<br>")}</div>
              <div class="recipient">
                <div class="name">${combinedName}</div>
                <div>${addr.line1}</div>
                ${addr.line2 ? `<div>${addr.line2}</div>` : ""}
              </div>
            ${stamps.map(stamp => {
              const pos = STAMP_POSITIONS[stamp.position] || STAMP_POSITIONS["top-right"];
              const posStyle = Object.entries(pos.style).map(([k, v]) => `${k.replace(/([A-Z])/g, '-$1').toLowerCase()}:${v}`).join(";");
              return `<div style="position:absolute;${posStyle};z-index:10;">${renderStampHtml(stamp)}</div>`;
            }).join("")}
              ${barcodeHtml}
            </div>
          `);
        });

        if (includeBarcode) {
          printWindow.document.write(`<script>
            window.addEventListener('load', function() {
              ${grouped.map(({ owner, customAddress }, idx) => {
                let addr;
                if (customAddress !== undefined) {
                  const { line1, line2 } = formatAddressLines(customAddress);
                  const zip = extractZip(line2) || extractZip(line1);
                  addr = { zip };
                } else {
                  addr = getOwnerAddress(owner);
                }
                if (!addr.zip) return "";
                return `try { JsBarcode("#bc-${idx}", "${addr.zip}", { format: "CODE128", height: 40, width: 1.5, displayValue: true, fontSize: 10, margin: 0 }); } catch(e) {}`;
              }).join("\n")}
            });
          <\/script>`);
        }

        printWindow.document.write("</body></html>");
        printWindow.document.close();
        printWindow.focus();
        const delay = includeBarcode ? 1500 : 500;
        setTimeout(() => printWindow.print(), delay);
      }
    }, 100);
  };

  const previewGrouped = getGroupedRecipients()[0];
  const previewAddr = previewGrouped
    ? (previewGrouped.customAddress !== undefined
        ? (() => { const { line1, line2 } = formatAddressLines(previewGrouped.customAddress); return { line1, line2 }; })()
        : getOwnerAddress(previewGrouped.owner))
    : null;
  const previewName = previewGrouped?.combinedName;

  return (
    <div className="flex flex-col gap-6 p-6 max-w-5xl">
      <div className="flex items-center gap-3">
        <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
          <Mail className="h-5 w-5 text-primary" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-foreground">Envelope Printing</h2>
          <p className="text-sm text-muted-foreground">{templates.currentTemplateId ? `Editing: ${templates.currentTemplateName}` : "New Draft"}</p>
        </div>
        <div className="ml-auto flex gap-1.5">
          <Button variant="outline" size="sm" className="gap-1 text-xs h-8" onClick={handleNew}><Plus className="h-3 w-3" /> New</Button>
          <LoadTemplateDialog templates={templates.savedTemplates} onLoad={handleLoad} onDelete={templates.deleteTemplate} />
          <Button variant="outline" size="sm" className="gap-1 text-xs h-8" onClick={handleSave}><Save className="h-3 w-3" /> Save</Button>
        </div>
      </div>

      <Separator />

      {/* Association Selector */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">Association</Label>
        <Select value={selectedAssoc} onValueChange={setSelectedAssoc}>
          <SelectTrigger className="w-full max-w-md text-sm">
            <SelectValue placeholder="Select association..." />
          </SelectTrigger>
          <SelectContent>
            {associations.map(a => (
              <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Envelope Settings */}
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <Settings className="h-4 w-4" /> Envelope Settings
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-1.5">
              <Label className="text-xs">Envelope Size</Label>
              <Select value={envelopeSize} onValueChange={setEnvelopeSize}>
                <SelectTrigger className="text-sm">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {Object.entries(ENVELOPE_SIZES).map(([k, v]) => (
                    <SelectItem key={k} value={k}>{v.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs">Return Address</Label>
              <textarea
                value={returnAddress}
                onChange={(e) => setReturnAddress(e.target.value)}
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus:outline-none focus:ring-2 focus:ring-ring"
              />
            </div>

            <div className="flex items-center gap-2">
              <Checkbox id="barcode" checked={includeBarcode} onCheckedChange={setIncludeBarcode} />
              <Label htmlFor="barcode" className="text-xs">Include postal barcode (USPS IMb)</Label>
            </div>


            {/* Stamps & Markings */}
            <Separator />
            <Accordion type="single" collapsible className="w-full">
              <AccordionItem value="stamps" className="border-none">
                <AccordionTrigger className="py-2 text-xs font-semibold text-muted-foreground hover:no-underline">
                  <div className="flex items-center gap-1.5"><Stamp className="h-3.5 w-3.5" /> Stamps & Markings ({stamps.length})</div>
                </AccordionTrigger>
                <AccordionContent className="pt-2 space-y-3">
                  <div className="space-y-1">
                    <Label className="text-[10px] uppercase tracking-wider text-muted-foreground">Quick Add Preset</Label>
                    <div className="flex flex-wrap gap-1">
                      {PRESET_STAMPS.map(p => (
                        <Button key={p.id} variant="outline" size="sm" className="text-[10px] h-6 px-2" onClick={() => addPresetStamp(p.id)}>{p.label}</Button>
                      ))}
                    </div>
                  </div>
                  <div className="flex gap-1">
                    <Button variant="outline" size="sm" className="text-[10px] h-6 px-2 gap-1" onClick={() => addStamp("text")}><Type className="h-3 w-3" /> Custom Text</Button>
                    <Button variant="outline" size="sm" className="text-[10px] h-6 px-2 gap-1" onClick={() => addStamp("image")}><Image className="h-3 w-3" /> Image URL</Button>
                  </div>
                  {stamps.map((stamp) => (
                    <div key={stamp.id} className="border rounded-md p-2.5 space-y-2 bg-muted/30">
                      <div className="flex items-center justify-between">
                        <span className="text-[10px] font-semibold text-muted-foreground uppercase">
                          {stamp.type === "preset" ? (PRESET_STAMPS.find(p => p.id === stamp.presetId)?.label || "Preset") : stamp.type === "image" ? "Image Stamp" : "Custom Text"}
                        </span>
                        <Button variant="ghost" size="sm" className="h-5 w-5 p-0 text-muted-foreground hover:text-destructive" onClick={() => removeStamp(stamp.id)}><Trash2 className="h-3 w-3" /></Button>
                      </div>
                      <div className="space-y-1">
                        <Label className="text-[10px]">Position</Label>
                        <Select value={stamp.position} onValueChange={(v) => updateStamp(stamp.id, "position", v)}>
                          <SelectTrigger className="h-7 text-[10px]"><SelectValue /></SelectTrigger>
                          <SelectContent>
                            {Object.entries(STAMP_POSITIONS).map(([k, v]) => (<SelectItem key={k} value={k} className="text-xs">{v.label}</SelectItem>))}
                          </SelectContent>
                        </Select>
                      </div>
                      {(stamp.type === "text" || stamp.type === "preset") && (
                        <div className="space-y-1">
                          <Label className="text-[10px]">Text</Label>
                          <Textarea value={stamp.text} onChange={(e) => updateStamp(stamp.id, "text", e.target.value)} className="text-xs min-h-[32px] h-8 resize-none" rows={1} />
                        </div>
                      )}
                      {stamp.type === "image" && (
                        <div className="space-y-1">
                          <Label className="text-[10px]">Image URL</Label>
                          <Input value={stamp.imageUrl} onChange={(e) => updateStamp(stamp.id, "imageUrl", e.target.value)} placeholder="https://..." className="text-xs h-7" />
                        </div>
                      )}
                      {stamp.type === "text" && (
                        <div className="grid grid-cols-3 gap-1.5">
                          <div className="space-y-0.5"><Label className="text-[9px]">Size (px)</Label><Input type="number" value={stamp.customStyle.fontSize} onChange={(e) => updateStampStyle(stamp.id, "fontSize", e.target.value)} className="h-6 text-[10px]" /></div>
                          <div className="space-y-0.5"><Label className="text-[9px]">Color</Label><Input type="color" value={stamp.customStyle.color} onChange={(e) => updateStampStyle(stamp.id, "color", e.target.value)} className="h-6 p-0.5" /></div>
                          <div className="space-y-0.5"><Label className="text-[9px]">Weight</Label>
                            <Select value={stamp.customStyle.fontWeight} onValueChange={(v) => updateStampStyle(stamp.id, "fontWeight", v)}>
                              <SelectTrigger className="h-6 text-[10px]"><SelectValue /></SelectTrigger>
                              <SelectContent><SelectItem value="normal" className="text-xs">Normal</SelectItem><SelectItem value="bold" className="text-xs">Bold</SelectItem></SelectContent>
                            </Select>
                          </div>
                          <div className="flex items-center gap-1 col-span-2"><Checkbox checked={stamp.customStyle.border} onCheckedChange={(v) => updateStampStyle(stamp.id, "border", v)} className="h-3 w-3" /><Label className="text-[9px]">Border</Label></div>
                          <div className="space-y-0.5"><Label className="text-[9px]">BG Color</Label><Input value={stamp.customStyle.background} onChange={(e) => updateStampStyle(stamp.id, "background", e.target.value)} placeholder="none" className="h-6 text-[10px]" /></div>
                        </div>
                      )}
                    </div>
                  ))}
                  {stamps.length === 0 && <p className="text-[10px] text-muted-foreground text-center py-2">No stamps added yet.</p>}
                </AccordionContent>
              </AccordionItem>
            </Accordion>

            <Separator />

            {/* Envelope Preview */}
            <div className="space-y-1.5">
              <Label className="text-xs text-muted-foreground">Preview</Label>
              <div
                className="border border-dashed border-border rounded-lg bg-muted/20 relative"
                style={{ aspectRatio: "9.5 / 4.125" }}
              >
                <div className="absolute top-3 left-4 text-[9px] text-muted-foreground whitespace-pre-line leading-tight">
                  {returnAddress}
                </div>
                {stamps.map(stamp => {
                  const pos = STAMP_POSITIONS[stamp.position] || STAMP_POSITIONS["top-right"];
                  return (
                    <div key={stamp.id} className="absolute z-10" style={{
                      ...pos.style,
                      transform: `${pos.style.transform || ""} scale(0.65)`.trim(),
                      transformOrigin: stamp.position.includes("right") ? "top right" : stamp.position.includes("center") ? "top center" : "top left",
                    }}>
                      {stamp.type === "image" && stamp.imageUrl ? (
                        <img src={stamp.imageUrl} className="max-h-8 max-w-20 object-contain" alt="stamp" />
                      ) : (
                        <span style={getStampInlineStyle(stamp)} className="inline-block">{stamp.text || "STAMP"}</span>
                      )}
                    </div>
                  );
                })}
                <div className="absolute bottom-4 left-1/2 -translate-x-1/4 text-[11px] text-muted-foreground text-center">
                  {previewAddr ? (
                    <>
                      <div className="font-medium">{previewName}</div>
                      <div>{previewAddr.line1}</div>
                      {previewAddr.line2 && <div>{previewAddr.line2}</div>}
                    </>
                  ) : (
                    <>
                      <div className="font-medium">Owner Name</div>
                      <div>123 Main Street</div>
                      <div>City, State ZIP</div>
                    </>
                  )}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Recipients */}
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <Users className="h-4 w-4" /> Recipients
              {owners.length > 0 && (
                <Badge variant="secondary" className="ml-auto text-[10px]">
                  {printMode === "selected" ? `${selectedOwnerIds.size} / ${owners.length}` : `${owners.length}`} owner(s)
                </Badge>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <RadioGroup value={printMode} onValueChange={setPrintMode} className="space-y-3">
              <div className="flex items-start gap-2">
                <RadioGroupItem value="all-owners" id="all" className="mt-0.5" />
                <div>
                  <Label htmlFor="all" className="text-xs font-medium">All Owners</Label>
                  <p className="text-[11px] text-muted-foreground">Print for every owner in selected association</p>
                </div>
              </div>
              <div className="flex items-start gap-2">
                <RadioGroupItem value="selected" id="selected" className="mt-0.5" />
                <div>
                  <Label htmlFor="selected" className="text-xs font-medium">Selected Owners</Label>
                  <p className="text-[11px] text-muted-foreground">Choose specific owners from the list below</p>
                </div>
              </div>
              <div className="flex items-start gap-2">
                <RadioGroupItem value="custom" id="custom" className="mt-0.5" />
                <div>
                  <Label htmlFor="custom" className="text-xs font-medium">Custom Address</Label>
                  <p className="text-[11px] text-muted-foreground">Enter a custom recipient name and address</p>
                </div>
              </div>
            </RadioGroup>

            {printMode === "custom" && (
              <div className="space-y-3 pt-2">
                <div className="space-y-1.5">
                  <Label className="text-xs">Recipient Name</Label>
                  <Input
                    value={customRecipientName}
                    onChange={(e) => setCustomRecipientName(e.target.value)}
                    placeholder="e.g. John & Jane Doe"
                    className="text-sm"
                  />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs">Recipient Address</Label>
                  <textarea
                    value={customRecipientAddress}
                    onChange={(e) => setCustomRecipientAddress(e.target.value)}
                    placeholder={"123 Main Street\nCity, State 12345"}
                    className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus:outline-none focus:ring-2 focus:ring-ring"
                  />
                </div>
              </div>
            )}

            {printMode === "selected" && (
              <>
                <Separator />
                <div className="flex items-center gap-2">
                  <Button variant="ghost" size="sm" className="text-[11px] h-6 px-2" onClick={selectAll}>Select All</Button>
                  <Button variant="ghost" size="sm" className="text-[11px] h-6 px-2" onClick={deselectAll}>Deselect All</Button>
                </div>
                {loadingOwners ? (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground py-4">
                    <Loader2 className="h-4 w-4 animate-spin" /> Loading owners...
                  </div>
                ) : owners.length === 0 ? (
                  <p className="text-xs text-muted-foreground py-2">No owners found. Select an association first.</p>
                ) : (
                  <ScrollArea className="h-[240px]">
                    <div className="space-y-1 pr-3">
                      {owners.map(owner => {
                        const addr = getOwnerAddress(owner);
                        return (
                          <label
                            key={owner.id}
                            className={`flex items-start gap-2 p-2 rounded-md cursor-pointer hover:bg-muted/50 transition-colors ${selectedOwnerIds.has(owner.id) ? "bg-primary/5 border border-primary/20" : "border border-transparent"}`}
                          >
                            <Checkbox
                              checked={selectedOwnerIds.has(owner.id)}
                              onCheckedChange={() => toggleOwner(owner.id)}
                              className="mt-0.5"
                            />
                            <div className="min-w-0">
                              <div className="text-xs font-medium truncate">{addr.name}</div>
                              <div className="text-[10px] text-muted-foreground truncate">{addr.line1}{addr.line2 ? `, ${addr.line2}` : ""}</div>
                            </div>
                          </label>
                        );
                      })}
                    </div>
                  </ScrollArea>
                )}
              </>
            )}

            {printMode === "all-owners" && !loadingOwners && owners.length > 0 && (
              <>
                <Separator />
                <p className="text-[11px] text-muted-foreground">
                  Will print {owners.length} envelope(s) for all active owners.
                </p>
              </>
            )}
          </CardContent>
        </Card>
      </div>

      <div className="flex items-center gap-2 pt-2" ref={printRef}>
        <Button size="sm" className="gap-1.5 text-xs" onClick={handlePrint}>
          <Printer className="h-3.5 w-3.5" /> Print Envelopes ({getGroupedRecipients().length})
        </Button>
      </div>
    </div>
  );
}
