import { useCallback, useEffect, useMemo, useState } from "react";
import { format } from "date-fns";
import { DragDropContext, Draggable, Droppable } from "@hello-pangea/dnd";
import {
  AlignLeft,
  ArrowLeft,
  Calendar,
  CheckSquare,
  Clock,
  Copy,
  ExternalLink,
  Eye,
  FileText,
  Globe,
  GripVertical,
  Hash,
  Heading,
  Loader2,
  Mail,
  Minus,
  MoveVertical,
  PenTool,
  Plus,
  Quote,
  Save,
  Settings,
  ToggleLeft,
  Trash2,
  Type,
  Upload,
  User,
  List,
} from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { useAssociation } from "@/contexts/AssociationContext";
import ContentBlocksEditor from "@/components/public-content/ContentBlocksEditor";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";

const FIELD_TYPES = [
  { type: "header", label: "Section Header", icon: Heading, isStatic: true },
  { type: "paragraph", label: "Instruction Text", icon: Quote, isStatic: true },
  { type: "spacer", label: "Spacer", icon: MoveVertical, isStatic: true },
  { type: "divider", label: "Divider", icon: Minus, isStatic: true },
  { type: "text", label: "Short Text", icon: Type },
  { type: "textarea", label: "Long Text", icon: AlignLeft },
  { type: "email", label: "Email", icon: Mail },
  { type: "name", label: "Full Name", icon: User },
  { type: "number", label: "Number", icon: Hash },
  { type: "date", label: "Date", icon: Calendar },
  { type: "time", label: "Time", icon: Clock },
  { type: "select", label: "Dropdown", icon: List },
  { type: "checkbox", label: "Checkbox", icon: CheckSquare },
  { type: "toggle", label: "Toggle", icon: ToggleLeft },
  { type: "file", label: "File Upload", icon: Upload },
  { type: "signature", label: "Signature", icon: PenTool },
];

function normalizeOptions(options) {
  if (Array.isArray(options)) return options.filter(Boolean).map((option) => String(option).trim()).filter(Boolean);
  if (typeof options === "string") return options.split(",").map((option) => option.trim()).filter(Boolean);
  return [];
}

function createField(type) {
  const base = {
    id: crypto.randomUUID(),
    type,
    label: "",
    placeholder: "",
    helpText: "",
    required: false,
    options: [],
    style: {},
  };

  if (type === "header") return { ...base, label: "New section" };
  if (type === "paragraph") return { ...base, label: "Add instructions for the person filling out this form." };
  if (type === "spacer") return { ...base, label: "Spacer", style: { height: "32px" } };
  if (type === "divider") return { ...base, label: "Divider" };
  if (type === "select") return { ...base, label: "Choose an option", options: ["Option 1", "Option 2"] };
  if (type === "checkbox") return { ...base, label: "Checkbox", placeholder: "Check to confirm" };
  if (type === "toggle") return { ...base, label: "Toggle", placeholder: "Yes / No" };
  if (type === "file") return { ...base, label: "Upload files" };
  if (type === "signature") return { ...base, label: "Signature" };

  return { ...base, label: `New ${type}` };
}

function getFieldLabel(field) {
  return FIELD_TYPES.find((item) => item.type === field.type)?.label || field.type;
}

function slugify(text) {
  return text.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
}

function extractSubmissionData(submission, fallbackFields = []) {
  const raw = submission?.form_data || {};
  if (raw.values && typeof raw.values === "object") {
    return {
      values: raw.values,
      fields: Array.isArray(raw.fields_snapshot) ? raw.fields_snapshot : fallbackFields,
    };
  }

  return {
    values: raw,
    fields: fallbackFields,
  };
}

function formatSubmissionValue(field, value) {
  if (value === null || value === undefined || value === "") return "—";
  if (field.type === "checkbox" || field.type === "toggle") return value ? "Yes" : "No";
  if (Array.isArray(value)) return `${value.length} file${value.length === 1 ? "" : "s"}`;
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}

function NativeSelect({ value, onChange, disabled = false, placeholder, options = [] }) {
  return (
    <select
      value={value || ""}
      onChange={(event) => onChange?.(event.target.value)}
      disabled={disabled}
      className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
    >
      <option value="">{placeholder}</option>
      {options.map((option) => (
        <option key={option.value} value={option.value}>
          {option.label}
        </option>
      ))}
    </select>
  );
}

function FieldEditor({ field, onChange, onRemove }) {
  const updateField = (key, value) => onChange({ ...field, [key]: value });
  const options = normalizeOptions(field.options).join("\n");

  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div className="space-y-1">
          <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{getFieldLabel(field)}</p>
          <p className="text-sm font-semibold text-foreground">{field.label || "Untitled field"}</p>
        </div>
        <Button type="button" variant="ghost" size="icon" className="h-8 w-8" onClick={onRemove}>
          <Trash2 className="h-4 w-4 text-destructive" />
        </Button>
      </div>

      <div className="mt-4 space-y-4">
        {field.type === "header" ? (
          <div className="space-y-2">
            <Label>Heading text</Label>
            <Input value={field.label || ""} onChange={(event) => updateField("label", event.target.value)} />
          </div>
        ) : null}

        {field.type === "paragraph" ? (
          <div className="space-y-2">
            <Label>Instruction text</Label>
            <Textarea value={field.label || ""} onChange={(event) => updateField("label", event.target.value)} className="min-h-[120px]" />
          </div>
        ) : null}

        {field.type === "spacer" ? (
          <div className="space-y-3">
            <div className="space-y-2">
              <Label>Spacer height</Label>
              <Input
                type="number"
                min="0"
                value={parseInt(field.style?.height || "32", 10)}
                onChange={(event) => updateField("style", { ...field.style, height: `${event.target.value || 0}px` })}
              />
            </div>
            <div className="rounded-md border border-dashed border-border bg-muted/20" style={{ height: field.style?.height || "32px" }} />
          </div>
        ) : null}

        {field.type === "divider" ? (
          <div className="space-y-2">
            <Label>Divider preview</Label>
            <Separator />
          </div>
        ) : null}

        {!["header", "paragraph", "spacer", "divider"].includes(field.type) ? (
          <>
            <div className="space-y-2">
              <Label>Field label</Label>
              <Input value={field.label || ""} onChange={(event) => updateField("label", event.target.value)} />
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label>Placeholder</Label>
                <Input value={field.placeholder || ""} onChange={(event) => updateField("placeholder", event.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Helper text</Label>
                <Input value={field.helpText || ""} onChange={(event) => updateField("helpText", event.target.value)} />
              </div>
            </div>

            {field.type === "select" ? (
              <div className="space-y-2">
                <Label>Options</Label>
                <Textarea
                  value={options}
                  onChange={(event) => updateField("options", event.target.value.split("\n").map((option) => option.trim()).filter(Boolean))}
                  className="min-h-[120px]"
                  placeholder="One option per line"
                />
              </div>
            ) : null}

            <div className="flex items-center justify-between rounded-lg border border-border bg-muted/20 px-3 py-3">
              <div>
                <p className="text-sm font-medium text-foreground">Required field</p>
                <p className="text-xs text-muted-foreground">Submission cannot be sent without this value.</p>
              </div>
              <Switch checked={Boolean(field.required)} onCheckedChange={(checked) => updateField("required", checked)} />
            </div>
          </>
        ) : null}
      </div>
    </div>
  );
}

function FormPreview({ title, description, fields }) {
  const previewFields = Array.isArray(fields) ? fields : [];

  return (
    <div className="space-y-4 rounded-xl border border-border bg-background p-5">
      <div>
        <h3 className="text-lg font-semibold text-foreground">{title || "Untitled form"}</h3>
        {description ? <p className="mt-1 text-sm text-muted-foreground">{description}</p> : null}
      </div>
      <Separator />

      <div className="space-y-4">
        {previewFields.length === 0 ? <p className="text-sm text-muted-foreground">Add fields to preview your public form.</p> : null}

        {previewFields.map((field) => {
          if (field.type === "header") return <h4 key={field.id} className="text-xl font-semibold text-foreground">{field.label}</h4>;
          if (field.type === "paragraph") return <p key={field.id} className="whitespace-pre-wrap text-sm text-muted-foreground">{field.label}</p>;
          if (field.type === "spacer") return <div key={field.id} style={{ height: field.style?.height || "32px" }} />;
          if (field.type === "divider") return <Separator key={field.id} />;

          return (
            <div key={field.id} className="space-y-2">
              <Label>
                {field.label || "Untitled field"}
                {field.required ? <span className="ml-1 text-destructive">*</span> : null}
              </Label>
              {["text", "email", "name", "number", "date", "time"].includes(field.type) ? <Input disabled placeholder={field.placeholder || ""} type={field.type === "number" ? "number" : field.type === "date" ? "date" : field.type === "time" ? "time" : field.type === "email" ? "email" : "text"} /> : null}
              {field.type === "textarea" ? <Textarea disabled className="min-h-[100px]" placeholder={field.placeholder || ""} /> : null}
              {field.type === "select" ? (
                normalizeOptions(field.options).length > 0 ? (
                  <select disabled className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-muted-foreground disabled:cursor-not-allowed disabled:opacity-100">
                    <option>{field.placeholder || "Select an option"}</option>
                    {normalizeOptions(field.options).map((option) => (
                      <option key={option}>{option}</option>
                    ))}
                  </select>
                ) : (
                  <div className="rounded-md border border-border bg-muted/20 px-3 py-3 text-sm text-muted-foreground">
                    Add dropdown options to preview this field.
                  </div>
                )
              ) : null}
              {field.type === "checkbox" ? <div className="rounded-md border border-border bg-muted/20 px-3 py-3 text-sm text-muted-foreground">Checkbox choice</div> : null}
              {field.type === "toggle" ? <div className="flex justify-end"><Switch disabled /></div> : null}
              {field.type === "file" ? <div className="rounded-md border border-dashed border-border px-4 py-6 text-center text-sm text-muted-foreground">File upload area</div> : null}
              {field.type === "signature" ? <div className="rounded-md border border-border bg-muted/20 px-4 py-10 text-center text-sm text-muted-foreground">Signature area</div> : null}
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default function PublicFormPage() {
  const { toast } = useToast();
  const associationContext = useAssociation() || {};
  const selectedAssociation = associationContext.selectedAssociation || null;

  const [associations, setAssociations] = useState([]);
  const [selectedAssociationId, setSelectedAssociationId] = useState("");
  const [templates, setTemplates] = useState([]);
  const [loadingAssociations, setLoadingAssociations] = useState(true);
  const [loadingTemplates, setLoadingTemplates] = useState(false);
  const [saving, setSaving] = useState(false);
  const [view, setView] = useState("list");
  const [selectedTemplateId, setSelectedTemplateId] = useState(null);
  const [selectedSubmission, setSelectedSubmission] = useState(null);
  const [submissions, setSubmissions] = useState([]);
  const [loadingSubmissions, setLoadingSubmissions] = useState(false);

  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [fields, setFields] = useState([]);
  const [isPublished, setIsPublished] = useState(false);
  const [requireAuth, setRequireAuth] = useState(false);
  const [allowAttachments, setAllowAttachments] = useState(true);
  const [bodyBlocks, setBodyBlocks] = useState([]);
  const [sidebarBlocks, setSidebarBlocks] = useState([]);
  const [sidebarEnabled, setSidebarEnabled] = useState(false);
  const [sidebarTitle, setSidebarTitle] = useState("");
  const [settings, setSettings] = useState({ organizationName: "", logoUrl: "" });

  const safeAssociations = useMemo(() => (Array.isArray(associations) ? associations : []), [associations]);
  const safeTemplates = useMemo(() => (Array.isArray(templates) ? templates : []), [templates]);

  const selectedTemplate = useMemo(
    () => safeTemplates.find((template) => template.id === selectedTemplateId) || null,
    [selectedTemplateId, safeTemplates]
  );

  const publicUrl = useMemo(() => {
    if (!selectedTemplate?.slug || typeof window === "undefined") return "";
    return `${window.location.origin}/public-form/${selectedTemplate.slug}`;
  }, [selectedTemplate?.slug]);

  const fetchAssociations = useCallback(async () => {
    setLoadingAssociations(true);

    try {
      const { data, error } = await supabase.from("associations").select("id, name, logo_url").order("name");
      if (error) throw error;

      const items = data || [];
      setAssociations(items);

      if (items.length > 0) {
        const matchedAssociation = items.find((item) => item.id === selectedAssociation?.id)
          || items.find((item) => item.name === selectedAssociation?.name)
          || items[0];

        setSelectedAssociationId((current) => current || matchedAssociation.id);
      }
    } catch (fetchError) {
      toast({ variant: "destructive", title: "Unable to load associations", description: fetchError.message });
    } finally {
      setLoadingAssociations(false);
    }
  }, [selectedAssociation?.id, selectedAssociation?.name, toast]);

  const fetchTemplates = useCallback(async (associationId = selectedAssociationId) => {
    if (!associationId) {
      setTemplates([]);
      return;
    }

    setLoadingTemplates(true);
    try {
      const { data, error } = await supabase
        .from("public_form_templates")
        .select("id, title, description, fields, settings, slug, is_published, require_auth, allow_attachments, updated_at")
        .eq("association_id", associationId)
        .order("updated_at", { ascending: false });

      if (error) throw error;
      setTemplates(data || []);
    } catch (fetchError) {
      toast({ variant: "destructive", title: "Unable to load public forms", description: fetchError.message });
    } finally {
      setLoadingTemplates(false);
    }
  }, [selectedAssociationId, toast]);

  const fetchSubmissions = useCallback(async (templateId) => {
    if (!templateId) return;

    setLoadingSubmissions(true);
    try {
      const { data, error } = await supabase
        .from("public_form_submissions")
        .select("id, submitter_name, submitter_email, form_data, attachments, status, created_at")
        .eq("template_id", templateId)
        .order("created_at", { ascending: false });

      if (error) throw error;
      setSubmissions(data || []);
    } catch (fetchError) {
      toast({ variant: "destructive", title: "Unable to load submissions", description: fetchError.message });
    } finally {
      setLoadingSubmissions(false);
    }
  }, [toast]);

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

  useEffect(() => {
    if (selectedAssociationId) fetchTemplates(selectedAssociationId);
  }, [fetchTemplates, selectedAssociationId]);

  useEffect(() => {
    if (!selectedAssociationId) return;
    const association = associations.find((item) => item.id === selectedAssociationId);
    if (!association) return;

    setSettings((previous) => {
      if (previous.organizationName || previous.logoUrl || selectedTemplateId) return previous;
      return {
        organizationName: association.name,
        logoUrl: association.logo_url || "",
      };
    });
  }, [associations, selectedAssociationId, selectedTemplateId]);

  const resetEditor = useCallback(() => {
    const association = associations.find((item) => item.id === selectedAssociationId);

    setSelectedTemplateId(null);
    setTitle("");
    setDescription("");
    setFields([]);
    setIsPublished(false);
    setRequireAuth(false);
    setAllowAttachments(true);
    setBodyBlocks([]);
    setSidebarBlocks([]);
    setSidebarEnabled(false);
    setSidebarTitle("");
    setSettings({
      organizationName: association?.name || "",
      logoUrl: association?.logo_url || "",
    });
  }, [associations, selectedAssociationId]);

  const openBuilder = () => {
    resetEditor();
    setView("builder");
  };

  const editTemplate = async (templateId) => {
    try {
      const { data, error } = await supabase.from("public_form_templates").select("*").eq("id", templateId).single();
      if (error) throw error;

      setSelectedTemplateId(data.id);
      setSelectedAssociationId(data.association_id);
      setTitle(data.title || "");
      setDescription(data.description || "");
      setFields(Array.isArray(data.fields) ? data.fields : []);
      setIsPublished(Boolean(data.is_published));
      setRequireAuth(Boolean(data.require_auth));
      setAllowAttachments(data.allow_attachments ?? true);
      setBodyBlocks(Array.isArray(data.body_blocks) ? data.body_blocks : []);
      setSidebarBlocks(Array.isArray(data.sidebar_blocks) ? data.sidebar_blocks : []);
      setSidebarEnabled(Boolean(data.sidebar_enabled));
      setSidebarTitle(data.sidebar_title || "");
      setSettings({
        organizationName: data.settings?.organizationName || "",
        logoUrl: data.settings?.logoUrl || "",
      });
      setView("builder");
    } catch (fetchError) {
      toast({ variant: "destructive", title: "Unable to open form", description: fetchError.message });
    }
  };

  const deleteTemplate = async (templateId) => {
    if (!window.confirm("Delete this form and its submissions?")) return;

    try {
      const { error } = await supabase.from("public_form_templates").delete().eq("id", templateId);
      if (error) throw error;
      toast({ title: "Public form deleted" });
      if (selectedTemplateId === templateId) resetEditor();
      fetchTemplates();
    } catch (deleteError) {
      toast({ variant: "destructive", title: "Delete failed", description: deleteError.message });
    }
  };

  const saveTemplate = async () => {
    if (!selectedAssociationId) {
      toast({ variant: "destructive", title: "Choose an association", description: "Public forms need to belong to an association." });
      return;
    }
    if (!title.trim()) {
      toast({ variant: "destructive", title: "Title required", description: "Add a title before saving this form." });
      return;
    }
    if (fields.length === 0) {
      toast({ variant: "destructive", title: "Add fields", description: "Build your form by adding at least one field." });
      return;
    }

    setSaving(true);

    try {
      const {
        data: { user },
      } = await supabase.auth.getUser();

      const payload = {
        association_id: selectedAssociationId,
        title: title.trim(),
        description: description.trim() || null,
        fields,
        settings,
        is_published: isPublished,
        require_auth: requireAuth,
        allow_attachments: allowAttachments,
        body_blocks: bodyBlocks,
        sidebar_blocks: sidebarBlocks,
        sidebar_enabled: sidebarEnabled,
        sidebar_title: sidebarTitle.trim() || null,
      };

      if (selectedTemplateId) {
        const { error } = await supabase.from("public_form_templates").update(payload).eq("id", selectedTemplateId);
        if (error) throw error;
        toast({ title: "Public form updated" });
      } else {
        const { data, error } = await supabase
          .from("public_form_templates")
          .insert({
            ...payload,
            slug: `${slugify(title)}-${Date.now().toString(36)}`,
            created_by: user?.id || null,
          })
          .select("id")
          .single();

        if (error) throw error;
        setSelectedTemplateId(data.id);
        toast({ title: "Public form created" });
      }

      await fetchTemplates(selectedAssociationId);
      setView("list");
    } catch (saveError) {
      toast({ variant: "destructive", title: "Save failed", description: saveError.message });
    } finally {
      setSaving(false);
    }
  };

  const openSubmissions = async (template) => {
    setSelectedTemplateId(template.id);
    setSelectedSubmission(null);
    setView("submissions");
    await fetchSubmissions(template.id);
  };

  const copyLink = async (slug) => {
    const url = `${window.location.origin}/public-form/${slug}`;
    await navigator.clipboard.writeText(url);
    toast({ title: "Link copied" });
  };

  const addField = (type) => setFields((previous) => [...previous, createField(type)]);
  const updateField = (fieldId, updatedField) => setFields((previous) => previous.map((field) => (field.id === fieldId ? updatedField : field)));
  const removeField = (fieldId) => setFields((previous) => previous.filter((field) => field.id !== fieldId));

  const onDragEnd = (result) => {
    if (!result.destination) return;

    setFields((previous) => {
      const items = [...previous];
      const [moved] = items.splice(result.source.index, 1);
      items.splice(result.destination.index, 0, moved);
      return items;
    });
  };

  const selectedAssociationOption = associations.find((item) => item.id === selectedAssociationId);
  const submissionView = selectedSubmission ? extractSubmissionData(selectedSubmission, selectedTemplate?.fields || []) : null;

  return (
    <div className="flex max-w-7xl flex-col gap-6 p-6">
      <div className="flex flex-col gap-4 rounded-2xl border border-border bg-card p-5 shadow-sm lg:flex-row lg:items-center lg:justify-between">
        <div className="flex items-start gap-3">
          <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary">
            <Globe className="h-5 w-5" />
          </div>
          <div>
            <h2 className="text-xl font-semibold text-foreground">Public Forms</h2>
            <p className="text-sm text-muted-foreground">Build shareable forms, publish them, and review incoming submissions.</p>
          </div>
        </div>

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <div className="min-w-[260px] space-y-1">
            <Label className="text-xs text-muted-foreground">Association</Label>
            <NativeSelect
              value={selectedAssociationId}
              onChange={setSelectedAssociationId}
              disabled={loadingAssociations}
              placeholder={loadingAssociations ? "Loading associations..." : "Select association"}
              options={safeAssociations.map((association) => ({ value: association.id, label: association.name }))}
            />
          </div>
          <Button onClick={openBuilder} className="gap-2 self-end">
            <Plus className="h-4 w-4" />
            New form
          </Button>
        </div>
      </div>

      {view === "list" ? (
        <div className="grid gap-6 lg:grid-cols-[1.4fr_0.9fr]">
          <Card>
            <CardHeader>
              <CardTitle>Your public forms</CardTitle>
              <CardDescription>Publish a form to generate a shareable submission link.</CardDescription>
            </CardHeader>
            <CardContent>
              {loadingTemplates ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" /> Loading forms...
                </div>
              ) : templates.length === 0 ? (
                <div className="rounded-xl border border-dashed border-border bg-muted/20 p-8 text-center">
                  <p className="text-sm font-medium text-foreground">No public forms yet</p>
                  <p className="mt-1 text-sm text-muted-foreground">Create one to start collecting submissions.</p>
                </div>
              ) : (
                <div className="grid gap-4">
                  {templates.map((template) => (
                    <div key={template.id} className="rounded-xl border border-border bg-background p-4">
                      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                        <div className="space-y-2">
                          <div className="flex flex-wrap items-center gap-2">
                            <h3 className="text-base font-semibold text-foreground">{template.title}</h3>
                            <span className={`rounded-full px-2 py-1 text-[11px] font-medium ${template.is_published ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"}`}>
                              {template.is_published ? "On website" : "Draft"}
                            </span>
                          </div>
                          {template.description ? <p className="text-sm text-muted-foreground">{template.description}</p> : null}
                          <p className="text-xs text-muted-foreground">Updated {format(new Date(template.updated_at), "PPP p")}</p>
                        </div>

                        <div className="flex flex-wrap gap-2">
                          <Button variant="outline" size="sm" onClick={() => editTemplate(template.id)}>
                            Edit
                          </Button>
                          <Button variant="outline" size="sm" onClick={() => openSubmissions(template)}>
                            Submissions
                          </Button>
                          {template.slug && template.is_published ? (
                            <>
                              <Button variant="outline" size="sm" className="gap-2" onClick={() => copyLink(template.slug)}>
                                <Copy className="h-4 w-4" /> Copy link
                              </Button>
                              <Button variant="outline" size="sm" asChild>
                                <a href={`${window.location.origin}/public-form/${template.slug}`} target="_blank" rel="noreferrer">
                                  <ExternalLink className="mr-2 h-4 w-4" /> Open
                                </a>
                              </Button>
                            </>
                          ) : null}
                          <Button variant="ghost" size="sm" onClick={() => deleteTemplate(template.id)}>
                            Delete
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>How it works</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 text-sm text-muted-foreground">
              <div className="rounded-xl border border-border bg-muted/20 p-4">
                <p className="font-medium text-foreground">1. Build</p>
                <p className="mt-1">Add sections, instructions, text fields, uploads, and signatures.</p>
              </div>
              <div className="rounded-xl border border-border bg-muted/20 p-4">
                <p className="font-medium text-foreground">2. Publish</p>
                <p className="mt-1">Turn on publishing to generate a live share link for homeowners or vendors.</p>
              </div>
              <div className="rounded-xl border border-border bg-muted/20 p-4">
                <p className="font-medium text-foreground">3. Review</p>
                <p className="mt-1">Open Submissions to read entries and download uploaded files.</p>
              </div>
            </CardContent>
          </Card>
        </div>
      ) : null}

      {view === "builder" ? (
        <div className="grid gap-6 lg:grid-cols-[0.95fr_1.25fr]">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <CardTitle>{selectedTemplateId ? "Edit public form" : "New public form"}</CardTitle>
                    <CardDescription>Choose the association, build the fields, and publish when it is ready.</CardDescription>
                  </div>
                  <Button variant="ghost" size="sm" className="gap-2" onClick={() => setView("list")}>
                    <ArrowLeft className="h-4 w-4" /> Back
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label>Association</Label>
                  <NativeSelect
                    value={selectedAssociationId}
                    onChange={setSelectedAssociationId}
                    placeholder="Select association"
                    options={safeAssociations.map((association) => ({ value: association.id, label: association.name }))}
                  />
                </div>

                <div className="space-y-2">
                  <Label>Form title</Label>
                  <Input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Maintenance request" />
                </div>

                <div className="space-y-2">
                  <Label>Description</Label>
                  <Textarea value={description} onChange={(event) => setDescription(event.target.value)} placeholder="Explain what the submitter should use this form for." className="min-h-[110px]" />
                </div>

                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label>Branding name</Label>
                    <Input value={settings.organizationName || ""} onChange={(event) => setSettings((previous) => ({ ...previous, organizationName: event.target.value }))} placeholder={selectedAssociationOption?.name || "Association name"} />
                  </div>
                  <div className="space-y-2">
                    <Label>Logo URL</Label>
                    <Input value={settings.logoUrl || ""} onChange={(event) => setSettings((previous) => ({ ...previous, logoUrl: event.target.value }))} placeholder="https://..." />
                  </div>
                </div>

                <Separator />

                <div className="space-y-3">
                  <div className="flex items-center justify-between rounded-lg border border-border bg-muted/20 px-3 py-3">
                    <div>
                      <p className="text-sm font-medium text-foreground">Publish to website</p>
                      <p className="text-xs text-muted-foreground">Show this form on the association's community page.</p>
                    </div>
                    <Switch checked={isPublished} onCheckedChange={setIsPublished} />
                  </div>
                  <div className="flex items-center justify-between rounded-lg border border-border bg-muted/20 px-3 py-3">
                    <div>
                      <p className="text-sm font-medium text-foreground">Require sign-in</p>
                      <p className="text-xs text-muted-foreground">Only authenticated users can submit.</p>
                    </div>
                    <Switch checked={requireAuth} onCheckedChange={setRequireAuth} />
                  </div>
                  <div className="flex items-center justify-between rounded-lg border border-border bg-muted/20 px-3 py-3">
                    <div>
                      <p className="text-sm font-medium text-foreground">Extra attachments</p>
                      <p className="text-xs text-muted-foreground">Allow additional uploads beyond file fields.</p>
                    </div>
                    <Switch checked={allowAttachments} onCheckedChange={setAllowAttachments} />
                  </div>
                </div>

                {publicUrl ? (
                  <div className="space-y-2 rounded-lg border border-border bg-muted/20 p-3">
                    <Label>Share link</Label>
                    <div className="flex gap-2">
                      <Input readOnly value={publicUrl} className="font-mono text-xs" />
                      <Button type="button" variant="outline" size="icon" onClick={() => copyLink(selectedTemplate.slug)}>
                        <Copy className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                ) : null}

                <div className="flex flex-wrap gap-2">
                  <Button onClick={saveTemplate} disabled={saving} className="gap-2">
                    {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
                    Save form
                  </Button>
                  <Button type="button" variant="outline" onClick={resetEditor}>Reset</Button>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Add form elements</CardTitle>
                <CardDescription>Drag fields on the right to reorder the public form.</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid gap-2 sm:grid-cols-2">
                  {FIELD_TYPES.map((item) => (
                    <Button key={item.type} type="button" variant="outline" className="justify-start gap-2" onClick={() => addField(item.type)}>
                      <item.icon className="h-4 w-4" />
                      {item.label}
                    </Button>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Custom Page Content</CardTitle>
                <CardDescription>Add headings, paragraphs, images, links, or callouts shown above the form fields on the public page.</CardDescription>
              </CardHeader>
              <CardContent>
                <ContentBlocksEditor value={bodyBlocks} onChange={setBodyBlocks} variant="main" />
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Information Sidebar</CardTitle>
                <CardDescription>Optional sidebar shown beside the form (e.g. instructions, deadlines, contacts).</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between rounded-lg border border-border bg-muted/20 px-3 py-3">
                  <div>
                    <p className="text-sm font-medium text-foreground">Show sidebar</p>
                    <p className="text-xs text-muted-foreground">Display this content beside the form on the public page.</p>
                  </div>
                  <Switch checked={sidebarEnabled} onCheckedChange={setSidebarEnabled} />
                </div>
                {sidebarEnabled ? (
                  <>
                    <div className="space-y-2">
                      <Label>Sidebar title (optional)</Label>
                      <Input value={sidebarTitle} onChange={(e) => setSidebarTitle(e.target.value)} placeholder="e.g. Before you submit" />
                    </div>
                    <ContentBlocksEditor value={sidebarBlocks} onChange={setSidebarBlocks} variant="sidebar" />
                  </>
                ) : null}
              </CardContent>
            </Card>
          </div>

          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <Settings className="h-4 w-4" /> Form structure
                </CardTitle>
                <CardDescription>Build the exact sequence people will see on the public page.</CardDescription>
              </CardHeader>
              <CardContent>
                {fields.length === 0 ? (
                  <div className="rounded-xl border border-dashed border-border bg-muted/20 p-8 text-center text-sm text-muted-foreground">
                    Add a field from the left to start building this public form.
                  </div>
                ) : (
                  <DragDropContext onDragEnd={onDragEnd}>
                    <Droppable droppableId="public-form-fields">
                      {(provided) => (
                        <div ref={provided.innerRef} {...provided.droppableProps} className="space-y-4">
                          {fields.map((field, index) => (
                            <Draggable key={field.id} draggableId={field.id} index={index}>
                              {(draggableProvided) => (
                                <div ref={draggableProvided.innerRef} {...draggableProvided.draggableProps} className="flex items-start gap-3">
                                  <div {...draggableProvided.dragHandleProps} className="mt-4 rounded-lg border border-border bg-muted/20 p-2 text-muted-foreground">
                                    <GripVertical className="h-4 w-4" />
                                  </div>
                                  <div className="min-w-0 flex-1">
                                    <FieldEditor field={field} onChange={(updatedField) => updateField(field.id, updatedField)} onRemove={() => removeField(field.id)} />
                                  </div>
                                </div>
                              )}
                            </Draggable>
                          ))}
                          {provided.placeholder}
                        </div>
                      )}
                    </Droppable>
                  </DragDropContext>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <Eye className="h-4 w-4" /> Live preview
                </CardTitle>
              </CardHeader>
              <CardContent>
                <FormPreview title={title} description={description} fields={fields} />
              </CardContent>
            </Card>
          </div>
        </div>
      ) : null}

      {view === "submissions" ? (
        <Card>
          <CardHeader>
            <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <CardTitle>Submissions for {selectedTemplate?.title || "public form"}</CardTitle>
                <CardDescription>Review responses, files, and submission timestamps.</CardDescription>
              </div>
              <Button variant="ghost" size="sm" className="gap-2 self-start" onClick={() => setView("list")}>
                <ArrowLeft className="h-4 w-4" /> Back to forms
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {loadingSubmissions ? (
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Loader2 className="h-4 w-4 animate-spin" /> Loading submissions...
              </div>
            ) : submissions.length === 0 ? (
              <div className="rounded-xl border border-dashed border-border bg-muted/20 p-8 text-center">
                <p className="text-sm font-medium text-foreground">No submissions yet</p>
                <p className="mt-1 text-sm text-muted-foreground">Once someone uses the public share link, responses will appear here.</p>
              </div>
            ) : (
              <div className="space-y-4">
                {submissions.map((submission) => {
                  const submissionData = extractSubmissionData(submission, selectedTemplate?.fields || []);
                  return (
                    <div key={submission.id} className="rounded-xl border border-border bg-background p-4">
                      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                        <div className="space-y-1">
                          <p className="text-sm font-semibold text-foreground">{submission.submitter_name || "Anonymous submitter"}</p>
                          <p className="text-sm text-muted-foreground">{submission.submitter_email || "No email provided"}</p>
                          <p className="text-xs text-muted-foreground">Submitted {format(new Date(submission.created_at), "PPP p")}</p>
                          <p className="text-xs text-muted-foreground">{submissionData.fields.length} response field{submissionData.fields.length === 1 ? "" : "s"}</p>
                        </div>
                        <Button variant="outline" size="sm" onClick={() => setSelectedSubmission(submission)}>
                          View details
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>
      ) : null}

      <Dialog open={Boolean(selectedSubmission)} onOpenChange={(open) => !open && setSelectedSubmission(null)}>
        <DialogContent className="max-h-[85vh] max-w-3xl overflow-hidden">
          <DialogHeader>
            <DialogTitle>Submission details</DialogTitle>
          </DialogHeader>

          {selectedSubmission && submissionView ? (
            <ScrollArea className="max-h-[70vh] pr-4">
              <div className="space-y-6">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="rounded-lg border border-border bg-muted/20 p-3">
                    <p className="text-xs uppercase tracking-wide text-muted-foreground">Submitter</p>
                    <p className="mt-1 text-sm font-medium text-foreground">{selectedSubmission.submitter_name || "Anonymous"}</p>
                    <p className="text-sm text-muted-foreground">{selectedSubmission.submitter_email || "No email provided"}</p>
                  </div>
                  <div className="rounded-lg border border-border bg-muted/20 p-3">
                    <p className="text-xs uppercase tracking-wide text-muted-foreground">Submitted</p>
                    <p className="mt-1 text-sm font-medium text-foreground">{format(new Date(selectedSubmission.created_at), "PPP p")}</p>
                    <p className="text-sm text-muted-foreground">Status: {selectedSubmission.status || "pending"}</p>
                  </div>
                </div>

                <div className="space-y-4">
                  {submissionView.fields.filter((field) => !["header", "paragraph", "spacer", "divider"].includes(field.type)).map((field) => {
                    const value = submissionView.values?.[field.id];
                    return (
                      <div key={field.id} className="rounded-lg border border-border bg-background p-4">
                        <p className="text-sm font-medium text-foreground">{field.label || getFieldLabel(field)}</p>
                        <div className="mt-2 text-sm text-muted-foreground">
                          {Array.isArray(value) && value.every((item) => item?.url) ? (
                            <div className="space-y-2">
                              {value.map((file, index) => (
                                <a key={`${file.url}-${index}`} href={file.url} target="_blank" rel="noreferrer" className="flex items-center gap-2 text-primary underline-offset-4 hover:underline">
                                  <ExternalLink className="h-4 w-4" /> {file.name || `Attachment ${index + 1}`}
                                </a>
                              ))}
                            </div>
                          ) : field.type === "signature" && typeof value === "string" && value.startsWith("data:image") ? (
                            <img src={value} alt={`${field.label || "Signature"} signature`} className="max-h-28 rounded-md border border-border bg-muted/20" />
                          ) : (
                            <p>{formatSubmissionValue(field, value)}</p>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>

                {Array.isArray(selectedSubmission.attachments) && selectedSubmission.attachments.length > 0 ? (
                  <div className="rounded-lg border border-border bg-background p-4">
                    <p className="text-sm font-medium text-foreground">Additional attachments</p>
                    <div className="mt-3 space-y-2">
                      {selectedSubmission.attachments.map((file, index) => (
                        <a key={`${file.url}-${index}`} href={file.url} target="_blank" rel="noreferrer" className="flex items-center gap-2 text-sm text-primary underline-offset-4 hover:underline">
                          <ExternalLink className="h-4 w-4" /> {file.name || `Attachment ${index + 1}`}
                        </a>
                      ))}
                    </div>
                  </div>
                ) : null}
              </div>
            </ScrollArea>
          ) : null}
        </DialogContent>
      </Dialog>
    </div>
  );
}
