import { useEffect, useRef, useState } from "react";
import { Bold, Download, FolderDown, IndentDecrease, IndentIncrease, ListChecks, Plus, RemoveFormatting, Save, Trash2, Video } 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 { Checkbox } from "@/components/ui/checkbox";
import { Textarea } from "@/components/ui/textarea";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { useSavedFormTemplates } from "@/hooks/useSavedFormTemplates";
import LoadTemplateDialog from "@/components/LoadTemplateDialog";
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { arrayMove, SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import SortableFormBlock from "./SortableFormBlock";
import jsPDF from "jspdf";
import { format } from "date-fns";
import QRCode from "qrcode";
import { embedValidationProof } from "@/lib/embedValidationProof";
import { storeValidatedPdf } from "@/lib/storeValidatedPdf";
import { SaveToDocumentsDialog } from "@/components/SaveToDocumentsDialog";
import { buildSecureStorageKey } from "@/lib/secureStorageNaming";
import { toast as sonnerToast } from "sonner";

const DEFAULT_ITEMS = [
  { id: "1", text: "Call to Order", indent: 0 },
  { id: "2", text: "Establish a Quorum of the Directors", indent: 0 },
  { id: "3", text: "Proof of Notice of Meeting", indent: 0 },
  { id: "4", text: "Approval of Prior Meeting Minutes", indent: 0 },
  { id: "5", text: "Reports of Officers and Committees", indent: 0 },
  { id: "6", text: "Old Business", indent: 0 },
  { id: "7", text: "New Business", indent: 0 },
  { id: "8", text: "Owner Forum", indent: 0 },
  { id: "9", text: "Next meeting date: TBD", indent: 0 },
  { id: "10", text: "Adjournment", indent: 0 },
];

const MAX_INDENT = 3;

const toRoman = (num) => {
  if (num <= 0) return "";
  const values = [
    [1000, "m"],
    [900, "cm"],
    [500, "d"],
    [400, "cd"],
    [100, "c"],
    [90, "xc"],
    [50, "l"],
    [40, "xl"],
    [10, "x"],
    [9, "ix"],
    [5, "v"],
    [4, "iv"],
    [1, "i"],
  ];

  let remainder = num;
  let result = "";

  values.forEach(([value, symbol]) => {
    while (remainder >= value) {
      result += symbol;
      remainder -= value;
    }
  });

  return result;
};

const getSiblingCount = (agendaItems, currentIndex) => {
  const currentItem = agendaItems[currentIndex];
  if (!currentItem) return 0;

  const currentIndent = currentItem.indent;
  let startIndex = -1;

  for (let i = currentIndex - 1; i >= 0; i -= 1) {
    if (agendaItems[i].indent < currentIndent) {
      startIndex = i;
      break;
    }
  }

  let count = 0;
  for (let i = startIndex + 1; i <= currentIndex; i += 1) {
    if (agendaItems[i].indent === currentIndent) {
      count += 1;
    }
  }

  return count;
};

const getIndentedMarker = (style, count) => {
  switch (style) {
    case "bullet":
      return "•";
    case "dash":
      return "–";
    case "arrow":
      return "▸";
    case "letter":
      return `${String.fromCharCode(96 + ((count - 1) % 26) + 1)}.`;
    case "roman":
      return `${toRoman(count)}.`;
    case "none":
      return "";
    default:
      return "•";
  }
};

const getMainMarker = (style, count) => {
  switch (style) {
    case "bullet":
      return "•";
    case "dash":
      return "–";
    case "arrow":
      return "▸";
    case "letter":
      return `${String.fromCharCode(64 + ((count - 1) % 26) + 1)}.`;
    case "roman":
      return `${toRoman(count).toUpperCase()}.`;
    case "number":
      return `${count}.`;
    case "none":
      return "";
    default:
      return `${count}.`;
  }
};

const getItemMarker = (agendaItems, currentIndex, mainStyle, subStyle) => {
  const item = agendaItems[currentIndex];
  if (!item) return "";
  const count = getSiblingCount(agendaItems, currentIndex);
  if (item.indent === 0) {
    return getMainMarker(mainStyle, count);
  }
  return getIndentedMarker(subStyle, count);
};

const fileToDataUrl = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });

const urlToDataUrl = async (url) => {
  if (!url) return null;
  if (url.startsWith("data:")) return url;

  const response = await fetch(url);
  if (!response.ok) {
    throw new Error("Failed to fetch logo image");
  }

  const blob = await response.blob();
  return fileToDataUrl(blob);
};

const getImageDimensions = (src) =>
  new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve({ width: img.naturalWidth, height: img.naturalHeight });
    img.onerror = reject;
    img.src = src;
  });

export default function MeetingAgendaForm() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState([]);
  const [selectedAssociation, setSelectedAssociation] = useState("");
  const [association, setAssociation] = useState(null);
  const [meetingDate, setMeetingDate] = useState(format(new Date(), "yyyy-MM-dd"));
  const [meetingTime, setMeetingTime] = useState("12:00");
  const [meetingLocation, setMeetingLocation] = useState("");
  const [meetingType, setMeetingType] = useState("Board of Directors");
  const [font, setFont] = useState("Helvetica");
  const [fontSize, setFontSize] = useState(9);
  const [items, setItems] = useState(DEFAULT_ITEMS);
  const [footerNotes, setFooterNotes] = useState("");
  const [zoomLink, setZoomLink] = useState("");
  const [zoomMeetingId, setZoomMeetingId] = useState("");
  const [zoomPasscode, setZoomPasscode] = useState("");
  const [showQrCode, setShowQrCode] = useState(false);
  const [embedValidation, setEmbedValidation] = useState(false);
  const [showSaveDocsDialog, setShowSaveDocsDialog] = useState(false);
  const [mainBulletStyle, setMainBulletStyle] = useState("number");
  const [subBulletStyle, setSubBulletStyle] = useState("bullet");
  const [openingParagraph, setOpeningParagraph] = useState("");
  const [logoUrl, setLogoUrl] = useState("");
  const [logoMode, setLogoMode] = useState("association");
  const logoInputRef = useRef(null);

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(KeyboardSensor),
  );

  const templates = useSavedFormTemplates("agenda");

  useEffect(() => {
    supabase
      .from("associations")
      .select("id, name")
      .eq("status", "active")
      .order("name")
      .then(({ data, error }) => {
        if (error) {
          console.error("Error loading associations:", error);
          return;
        }

        if (data) setAssociations(data);
      });
  }, []);

  useEffect(() => {
    let active = true;

    if (!selectedAssociation) {
      setAssociation(null);
      if (logoMode === "association") setLogoUrl("");
      return undefined;
    }

    supabase
      .from("associations")
      .select("*")
      .eq("id", selectedAssociation)
      .single()
      .then(({ data, error }) => {
        if (!active) return;
        if (error) {
          console.error("Error loading association:", error);
          return;
        }

        if (data) {
          setAssociation(data);
          if (logoMode === "association") {
            setLogoUrl(data.logo_url || "");
          }
        }
      });

    return () => {
      active = false;
    };
  }, [selectedAssociation, logoMode]);

  const handleDragEnd = (event) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;

    setItems((prev) => {
      const oldIndex = prev.findIndex((item) => item.id === active.id);
      const newIndex = prev.findIndex((item) => item.id === over.id);
      return arrayMove(prev, oldIndex, newIndex);
    });
  };

  const handleLogoFileChange = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith("image/")) {
      toast({
        variant: "destructive",
        title: "Invalid file",
        description: "Please choose an image file for the agenda logo.",
      });
      return;
    }

    try {
      const dataUrl = await fileToDataUrl(file);
      setLogoMode("custom");
      setLogoUrl(String(dataUrl || ""));
    } catch (error) {
      console.error("Error loading logo:", error);
      toast({
        variant: "destructive",
        title: "Logo upload failed",
        description: "We couldn't read that image file.",
      });
    } finally {
      if (logoInputRef.current) logoInputRef.current.value = "";
    }
  };

  const handleUseAssociationLogo = () => {
    setLogoMode("association");
    setLogoUrl(association?.logo_url || "");
  };

  const clearLogo = () => {
    setLogoMode("none");
    setLogoUrl("");
    if (logoInputRef.current) logoInputRef.current.value = "";
  };

  const getFormData = () => ({
    selectedAssociation,
    meetingDate,
    meetingTime,
    meetingLocation,
    meetingType,
    font,
    fontSize,
    items,
    footerNotes,
    zoomLink,
    zoomMeetingId,
    zoomPasscode,
    showQrCode,
    mainBulletStyle,
    subBulletStyle,
    openingParagraph,
    logoUrl,
    logoMode,
  });

  const applyFormData = (data) => {
    if (data.logoMode !== undefined) setLogoMode(data.logoMode);
    else if (data.logoUrl) setLogoMode("custom");

    if (data.logoUrl !== undefined) setLogoUrl(data.logoUrl);
    if (data.selectedAssociation !== undefined) setSelectedAssociation(data.selectedAssociation);
    if (data.meetingDate !== undefined) setMeetingDate(data.meetingDate);
    if (data.meetingTime !== undefined) setMeetingTime(data.meetingTime);
    if (data.meetingLocation !== undefined) setMeetingLocation(data.meetingLocation);
    if (data.meetingType !== undefined) setMeetingType(data.meetingType);
    if (data.font !== undefined) setFont(data.font);
    if (data.fontSize !== undefined) setFontSize(Number(data.fontSize));
    if (data.items !== undefined) setItems(data.items);
    if (data.footerNotes !== undefined) setFooterNotes(data.footerNotes);
    if (data.zoomLink !== undefined) setZoomLink(data.zoomLink);
    if (data.zoomMeetingId !== undefined) setZoomMeetingId(data.zoomMeetingId);
    if (data.zoomPasscode !== undefined) setZoomPasscode(data.zoomPasscode);
    if (data.showQrCode !== undefined) setShowQrCode(Boolean(data.showQrCode));
    if (data.mainBulletStyle !== undefined) setMainBulletStyle(data.mainBulletStyle);
    else if (data.bulletStyle !== undefined) setMainBulletStyle(data.bulletStyle === "number" || !data.bulletStyle ? "number" : data.bulletStyle);
    if (data.subBulletStyle !== undefined) setSubBulletStyle(data.subBulletStyle);
    else if (data.bulletStyle !== undefined) setSubBulletStyle(data.bulletStyle);
    if (data.openingParagraph !== undefined) setOpeningParagraph(data.openingParagraph);
  };

  const handleSave = async () => {
    const name = `${meetingType} Agenda - ${meetingDate}`;
    await templates.saveTemplate(name, getFormData(), selectedAssociation || null);
  };

  const handleLoad = async (templateId) => {
    const result = await templates.loadTemplate(templateId);
    if (result?.form_data) applyFormData(result.form_data);
  };

  const handleNew = () => {
    templates.newTemplate();
    setSelectedAssociation("");
    setAssociation(null);
    setMeetingDate(format(new Date(), "yyyy-MM-dd"));
    setMeetingTime("12:00");
    setMeetingLocation("");
    setMeetingType("Board of Directors");
    setFont("Helvetica");
    setFontSize(9);
    setItems(DEFAULT_ITEMS);
    setFooterNotes("");
    setZoomLink("");
    setZoomMeetingId("");
    setZoomPasscode("");
    setShowQrCode(false);
    setMainBulletStyle("number");
    setSubBulletStyle("bullet");
    setOpeningParagraph("");
    setLogoMode("association");
    setLogoUrl("");
    if (logoInputRef.current) logoInputRef.current.value = "";
  };

  const addItem = () => {
    setItems((prev) => [...prev, { id: Date.now().toString(), text: "", indent: 0, isBold: false, isPlainText: false }]);
  };

  const updateItem = (id, text) => {
    setItems((prev) => prev.map((item) => (item.id === id ? { ...item, text } : item)));
  };

  const removeItem = (id) => {
    setItems((prev) => prev.filter((item) => item.id !== id));
  };

  const indentItem = (id, direction) => {
    setItems((prev) =>
      prev.map((item) =>
        item.id === id
          ? { ...item, indent: Math.max(0, Math.min(MAX_INDENT, item.indent + direction)) }
          : item,
      ),
    );
  };

  const buildPdf = async () => {
    const doc = new jsPDF({ unit: "pt", format: "letter" });
    const margin = 60;
    const pageW = doc.internal.pageSize.getWidth();
    const pageH = doc.internal.pageSize.getHeight();
    let y = 60;

    const activeLogoUrl =
      logoMode === "association"
        ? association?.logo_url || logoUrl
        : logoMode === "custom"
          ? logoUrl
          : "";

    if (activeLogoUrl) {
      try {
        const dataUrl = await urlToDataUrl(activeLogoUrl);
        if (dataUrl) {
          const { width, height } = await getImageDimensions(dataUrl);
          const maxLogoH = 60;
          const maxLogoW = 200;
          const scale = Math.min(maxLogoW / width, maxLogoH / height, 1);
          const logoW = width * scale;
          const logoH = height * scale;
          doc.addImage(dataUrl, "PNG", (pageW - logoW) / 2, y, logoW, logoH);
          y += logoH + 12;
        }
      } catch (error) {
        console.error("Failed to load logo for PDF:", error);
      }
    }

    doc.setFontSize(14);
    doc.setFont("helvetica", "bold");
    const title = association ? association.name : "Meeting Agenda";
    doc.text(title, pageW / 2, y, { align: "center" });
    y += 20;

    doc.setFontSize(11);
    doc.setFont("helvetica", "normal");
    doc.text(`${meetingType} Meeting Agenda`, pageW / 2, y, { align: "center" });
    y += 30;

    doc.setFontSize(fontSize);
    if (meetingDate) {
      doc.text(`Date: ${format(new Date(`${meetingDate}T12:00:00`), "MMMM d, yyyy")}`, margin, y);
      y += 14;
    }
    if (meetingTime) {
      doc.text(`Time: ${meetingTime}`, margin, y);
      y += 14;
    }
    if (meetingLocation) {
      doc.text(`Location: ${meetingLocation}`, margin, y);
      y += 14;
    }
    if (openingParagraph.trim()) {
      y += 6;
      doc.setFont("helvetica", "normal");
      doc.setFontSize(fontSize);
      const paraLines = doc.splitTextToSize(openingParagraph, pageW - margin * 2);
      paraLines.forEach((line) => {
        if (y > 700) {
          doc.addPage();
          y = 60;
        }
        doc.text(line, margin, y);
        y += 14;
      });
      y += 6;
    }

    y += 10;
    doc.line(margin, y, pageW - margin, y);
    y += 15;

    items.forEach((item, index) => {
      if (y > 700) {
        doc.addPage();
        y = 60;
      }

      const indent = item.indent * 20;
      const marker = item.isPlainText ? "" : getItemMarker(items, index, mainBulletStyle, subBulletStyle);
      const markerX = margin + indent;
      const textX = marker ? markerX + 20 : markerX + (item.isPlainText ? 20 : 0);

      const shouldBold = item.isBold || (item.indent === 0 && !item.isPlainText);
      doc.setFont("helvetica", shouldBold ? "bold" : "normal");
      if (marker) doc.text(marker, markerX, y);
      doc.text(item.text, textX, y);
      if (shouldBold) doc.setFont("helvetica", "normal");

      y += 16;
    });

    if (footerNotes.trim()) {
      y += 10;
      doc.setFont("helvetica", "normal");
      doc.setFontSize(fontSize);
      const noteLines = doc.splitTextToSize(footerNotes, pageW - margin * 2);
      noteLines.forEach((line) => {
        if (y > 700) {
          doc.addPage();
          y = 60;
        }
        doc.text(line, margin, y);
        y += 14;
      });
    }

    if (zoomLink || zoomMeetingId || zoomPasscode) {
      y += 16;
      if (y > 660) {
        doc.addPage();
        y = 60;
      }

      doc.line(margin, y, pageW - margin, y);
      y += 16;
      doc.setFont("helvetica", "bold");
      doc.setFontSize(fontSize);
      doc.text("Virtual Meeting Information", margin, y);
      y += 16;
      doc.setFont("helvetica", "normal");

      if (zoomLink) {
        doc.text(`Join Link: ${zoomLink}`, margin, y);
        y += 14;
      }
      if (zoomMeetingId) {
        doc.text(`Meeting ID: ${zoomMeetingId}`, margin, y);
        y += 14;
      }
      if (zoomPasscode) {
        doc.text(`Passcode: ${zoomPasscode}`, margin, y);
        y += 14;
      }

      if (showQrCode && zoomLink) {
        try {
          const qrDataUrl = await QRCode.toDataURL(zoomLink, { width: 100, margin: 1 });
          y += 6;
          if (y + 100 > pageH - 40) {
            doc.addPage();
            y = 60;
          }
          doc.addImage(qrDataUrl, "PNG", margin, y, 80, 80);
          doc.setFontSize(7);
          doc.text("Scan to join", margin, y + 90);
          y += 100;
        } catch (error) {
          console.error("QR code generation failed:", error);
        }
      }
    }

    let validationProof = null;

    if (embedValidation) {
      try {
        const docDate = meetingDate ? format(new Date(`${meetingDate}T12:00:00`), "MMMM d, yyyy") : "";
        validationProof = await embedValidationProof(doc, {
          documentTitle: `${meetingType} Meeting Agenda${association ? ` – ${association.name}` : ""}`,
          documentType: "Meeting Agenda",
          documentDate: docDate,
          associationId: selectedAssociation || undefined,
        });
      } catch (err) {
        console.error("Failed to embed validation proof:", err);
      }
    }

    return { doc, validationProof };
  };

  const exportPDF = async () => {
    const { doc, validationProof } = await buildPdf();
    const pdfFileName = `Agenda_${format(new Date(), "yyyy-MM-dd")}.pdf`;

    let validatedPdfStored = false;
    if (validationProof) {
      try {
        const url = await storeValidatedPdf(doc, validationProof.id, pdfFileName);
        if (url) validatedPdfStored = true;
      } catch (err) {
        console.error("Failed to store validated PDF:", err);
      }
    }

    doc.save(pdfFileName);

    if (validatedPdfStored) {
      sonnerToast.success("Agenda PDF exported", { description: "Validation certificate embedded and saved." });
    } else if (embedValidation) {
      sonnerToast.warning("Agenda PDF exported, but validation storage failed");
    } else {
      sonnerToast.success("Agenda PDF exported");
    }
  };

  const handleSaveToDocuments = async (metadata) => {
    const { doc, validationProof } = await buildPdf();
    const blob = doc.output("blob");
    const pdfFileName = `Agenda_${format(new Date(), "yyyy-MM-dd")}.pdf`;

    const { data: userData } = await supabase.auth.getUser();
    if (!userData?.user) throw new Error("Not authenticated");

    // Store validation copy
    if (validationProof) {
      try {
        await storeValidatedPdf(doc, validationProof.id, pdfFileName);
      } catch (err) {
        console.error("Failed to store validated PDF:", err);
      }
    }

    // Upload to documents storage
    // Display name kept human-readable; storage key is randomized.
    const displayFileName = `${metadata.name.replace(/[^a-zA-Z0-9._ -]+/g, "_").trim()}.pdf`;
    const filePath = buildSecureStorageKey("doc.pdf", userData.user.id);

    const { error: uploadError } = await supabase.storage
      .from("files")
      .upload(filePath, blob, { contentType: "application/pdf" });
    if (uploadError) throw uploadError;

    const { data: { publicUrl } } = supabase.storage.from("files").getPublicUrl(filePath);

    const { error: docError } = await supabase.from("documents").insert({
      title: metadata.name,
      file_url: publicUrl,
      file_name: displayFileName,
      file_size: blob.size,
      association_id: metadata.clientId,
      category: metadata.category || "general",
      uploaded_by: userData.user.id,
    });
    if (docError) throw docError;

    sonnerToast.success("Agenda saved to Documents", {
      description: validationProof ? "Validation certificate embedded." : undefined,
    });
    return { blob };
  };

  return (
    <div className="flex gap-6 p-6 h-full min-h-0">
      <div className="w-[320px] flex-shrink-0 space-y-4">
        <div className="flex items-center gap-3">
          <div className="h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center">
            <ListChecks className="h-4 w-4 text-primary" />
          </div>
          <div>
            <h2 className="text-base font-semibold text-foreground">Meeting Agenda Editor</h2>
            <p className="text-xs text-muted-foreground">
              {templates.currentTemplateId ? `Editing: ${templates.currentTemplateName}` : "New unsaved agenda"}
            </p>
          </div>
          <div className="ml-auto flex gap-1.5">
            <Button type="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 type="button" variant="outline" size="sm" className="gap-1 text-xs h-8" onClick={handleSave}>
              <Save className="h-3 w-3" /> Save
            </Button>
          </div>
        </div>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm flex items-center gap-2">📅 Meeting Details</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex gap-3">
              <div className="space-y-1 flex-1">
                <Label className="text-xs">Font</Label>
                <Select value={font} onValueChange={setFont}>
                  <SelectTrigger className="h-8 text-xs"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Helvetica">Helvetica</SelectItem>
                    <SelectItem value="Times">Times</SelectItem>
                    <SelectItem value="Courier">Courier</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1 w-[70px]">
                <Label className="text-xs">Size (pt)</Label>
                <Input type="number" value={fontSize} onChange={(e) => setFontSize(Number(e.target.value))} className="h-8 text-xs" />
              </div>
            </div>

            <div className="space-y-1">
              <Label className="text-xs">Main Bullet Style</Label>
              <Select value={mainBulletStyle} onValueChange={setMainBulletStyle}>
                <SelectTrigger className="h-8 text-xs"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="number">1. Number</SelectItem>
                  <SelectItem value="bullet">• Bullet</SelectItem>
                  <SelectItem value="dash">– Dash</SelectItem>
                  <SelectItem value="arrow">▸ Arrow</SelectItem>
                  <SelectItem value="letter">A. Letter</SelectItem>
                  <SelectItem value="roman">I. Roman</SelectItem>
                  <SelectItem value="none">No marker</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1">
              <Label className="text-xs">Sub-bullet Style</Label>
              <Select value={subBulletStyle} onValueChange={setSubBulletStyle}>
                <SelectTrigger className="h-8 text-xs"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="bullet">• Bullet</SelectItem>
                  <SelectItem value="dash">– Dash</SelectItem>
                  <SelectItem value="arrow">▸ Arrow</SelectItem>
                  <SelectItem value="letter">a. Letter</SelectItem>
                  <SelectItem value="roman">i. Roman</SelectItem>
                  <SelectItem value="none">No marker</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1">
              <Label className="text-xs">Association (Client)</Label>
              <Select value={selectedAssociation} onValueChange={setSelectedAssociation}>
                <SelectTrigger className="text-xs"><SelectValue placeholder="Select Association" /></SelectTrigger>
                <SelectContent>
                  {associations.map((item) => (
                    <SelectItem key={item.id} value={item.id}>{item.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1">
              <Label className="text-xs">Top Logo</Label>
              <input
                ref={logoInputRef}
                type="file"
                accept="image/*"
                onChange={handleLogoFileChange}
                className="hidden"
              />
              <div className="flex flex-wrap items-center gap-2">
                <Button type="button" variant="outline" size="sm" className="h-8 text-xs" onClick={() => logoInputRef.current?.click()}>
                  Browse...
                </Button>
                {association?.logo_url && logoMode !== "association" && (
                  <Button type="button" variant="outline" size="sm" className="h-8 text-xs" onClick={handleUseAssociationLogo}>
                    Use Client Logo
                  </Button>
                )}
                {logoUrl ? (
                  <button type="button" onClick={clearLogo} className="text-xs text-destructive hover:underline">
                    Remove
                  </button>
                ) : null}
              </div>
              {logoUrl ? (
                <div className="rounded-md border border-border bg-muted/20 p-2">
                  <img src={logoUrl} alt="Agenda logo preview" className="h-12 max-w-full object-contain" />
                  <p className="mt-1 text-[10px] text-muted-foreground">
                    {logoMode === "association" ? "Using client logo" : "Using custom uploaded logo"}
                  </p>
                </div>
              ) : (
                <p className="text-xs text-muted-foreground">No logo selected.</p>
              )}
            </div>

            <div className="space-y-1">
              <Label className="text-xs">Meeting Date</Label>
              <Input type="date" value={meetingDate} onChange={(e) => setMeetingDate(e.target.value)} className="h-8 text-xs" />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Meeting Time</Label>
              <Input value={meetingTime} onChange={(e) => setMeetingTime(e.target.value)} placeholder="12:00 p.m." className="h-8 text-xs" />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Location</Label>
              <Input value={meetingLocation} onChange={(e) => setMeetingLocation(e.target.value)} placeholder="Microsoft Teams" className="h-8 text-xs" />
            </div>
            <div className="space-y-1">
              <Label className="text-xs">Meeting Type</Label>
              <Input value={meetingType} onChange={(e) => setMeetingType(e.target.value)} placeholder="Board of Directors" className="h-8 text-xs" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm flex items-center gap-2"><Video className="h-4 w-4" /> Virtual Meeting / Zoom</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="space-y-1">
              <Label className="text-xs">Join Link</Label>
              <Input value={zoomLink} onChange={(e) => setZoomLink(e.target.value)} placeholder="https://zoom.us/j/..." className="h-8 text-xs" />
            </div>
            <div className="flex gap-3">
              <div className="space-y-1 flex-1">
                <Label className="text-xs">Meeting ID</Label>
                <Input value={zoomMeetingId} onChange={(e) => setZoomMeetingId(e.target.value)} placeholder="123 456 7890" className="h-8 text-xs" />
              </div>
              <div className="space-y-1 flex-1">
                <Label className="text-xs">Passcode</Label>
                <Input value={zoomPasscode} onChange={(e) => setZoomPasscode(e.target.value)} placeholder="abc123" className="h-8 text-xs" />
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Checkbox id="showQr" checked={showQrCode} onCheckedChange={(checked) => setShowQrCode(Boolean(checked))} />
              <Label htmlFor="showQr" className="text-xs cursor-pointer">Include QR code for join link</Label>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm flex items-center gap-2">🔒 Validation</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex items-center gap-2">
              <Checkbox id="embedValidation" checked={embedValidation} onCheckedChange={(checked) => setEmbedValidation(Boolean(checked))} />
              <Label htmlFor="embedValidation" className="text-xs cursor-pointer">Embed validation certificate in PDF footer</Label>
            </div>
          </CardContent>
        </Card>
      </div>

      <Separator orientation="vertical" />

      <div className="flex-1 flex flex-col min-h-0">
        <div className="space-y-1 mb-3">
          <Label className="text-xs font-medium">Opening Paragraph (below header, above items)</Label>
          <Textarea
            value={openingParagraph}
            onChange={(e) => setOpeningParagraph(e.target.value)}
            placeholder="e.g. Notice is hereby given that a meeting of the Board of Directors will be held..."
            className="text-xs min-h-[50px]"
          />
        </div>

        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-semibold">Agenda Items</h3>
          <Button type="button" variant="outline" size="sm" className="gap-1.5 text-xs" onClick={addItem}>
            <Plus className="h-3.5 w-3.5" /> Add Item
          </Button>
        </div>

        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
          <SortableContext items={items.map((item) => item.id)} strategy={verticalListSortingStrategy}>
            <div className="flex-1 overflow-auto border rounded-lg bg-card p-4 space-y-1">
              {items.map((item, index) => {
                const marker = item.isPlainText ? "" : getItemMarker(items, index, mainBulletStyle, subBulletStyle);

                return (
                  <SortableFormBlock key={item.id} id={item.id}>
                    <div className="flex items-center gap-1.5 flex-1" style={{ paddingLeft: `${item.indent * 28}px` }}>
                      {marker ? <span className="text-xs font-medium text-muted-foreground w-8 text-right shrink-0">{marker}</span> : null}
                      <Input
                        value={item.text}
                        onChange={(e) => updateItem(item.id, e.target.value)}
                        className={`h-8 text-sm flex-1 ${item.isBold ? "font-bold" : ""}`}
                        placeholder={item.isPlainText ? "Plain text entry..." : "Agenda item..."}
                      />
                      <div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button
                          type="button"
                          onClick={() => setItems((prev) => prev.map((i) => i.id === item.id ? { ...i, isBold: !i.isBold } : i))}
                          className={`p-1 ${item.isBold ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
                          title="Toggle bold"
                        >
                          <Bold className="h-3.5 w-3.5" />
                        </button>
                        <button
                          type="button"
                          onClick={() => setItems((prev) => prev.map((i) => i.id === item.id ? { ...i, isPlainText: !i.isPlainText } : i))}
                          className={`p-1 ${item.isPlainText ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
                          title="Toggle plain text (no bullet marker)"
                        >
                          <RemoveFormatting className="h-3.5 w-3.5" />
                        </button>
                        <button type="button" onClick={() => indentItem(item.id, -1)} className="p-1 text-muted-foreground hover:text-foreground" title="Outdent">
                          <IndentDecrease className="h-3.5 w-3.5" />
                        </button>
                        <button type="button" onClick={() => indentItem(item.id, 1)} className="p-1 text-muted-foreground hover:text-foreground" title="Indent">
                          <IndentIncrease className="h-3.5 w-3.5" />
                        </button>
                        <button type="button" onClick={() => removeItem(item.id)} className="p-1 text-destructive/70 hover:text-destructive">
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    </div>
                  </SortableFormBlock>
                );
              })}
            </div>
          </SortableContext>
        </DndContext>

        <div className="mt-3 space-y-1">
          <Label className="text-xs font-medium">Additional Notes (below agenda items)</Label>
          <Textarea
            value={footerNotes}
            onChange={(e) => setFooterNotes(e.target.value)}
            placeholder="Add any additional information to appear below the agenda items..."
            className="text-xs min-h-[60px]"
          />
        </div>

        <div className="flex items-center gap-2 mt-4">
          <Button type="button" variant="outline" size="sm" className="gap-1.5 text-xs" onClick={() => setShowSaveDocsDialog(true)}>
            <FolderDown className="h-3.5 w-3.5" /> Save to Docs
          </Button>
          <Button type="button" size="sm" className="gap-1.5 text-xs" onClick={exportPDF}>
            <Download className="h-3.5 w-3.5" /> Export PDF
          </Button>
        </div>
      </div>

      <SaveToDocumentsDialog
        open={showSaveDocsDialog}
        onOpenChange={setShowSaveDocsDialog}
        onSave={handleSaveToDocuments}
        defaultName={`${meetingType} Meeting Agenda${association ? ` – ${association.name}` : ""}`}
        defaultClientId={selectedAssociation}
      />
    </div>
  );
}
