import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { useServerFn } from "@tanstack/react-start";
import {
  createForm,
  deleteForm,
  getFormAdmin,
  listForms,
  listFormSessions,
  saveForm,
} from "@/lib/forms.functions";
import { FormMetricsPanel } from "./FormMetricsPanel";
import { MetaConversionsPanel } from "./MetaConversionsPanel";
import { handleAuthErrorOrThrow, isAuthError } from "@/lib/handle-auth-error";


type Stats = { views: number; starts: number; submissions: number };
type FormListItem = {
  id: string;
  slug: string;
  name: string;
  is_active: boolean;
  created_at: string;
  stats: Stats;
};

type FormFull = {
  id: string;
  slug: string;
  name: string;
  welcome_title: string;
  welcome_subtitle: string;
  welcome_cta: string;
  thank_you_title: string;
  thank_you_message: string;
  primary_color: string;
  background_color: string;
  text_color: string;
  highlight_color: string;
  send_to_meta: boolean;
  show_cal: boolean;
  is_active: boolean;
};


type Question = {
  id?: string;
  position: number;
  type: "short_text" | "long_text" | "email" | "phone" | "number" | "radio" | "checkbox";
  label: string;
  description: string;
  required: boolean;
  options: string[];
};

type Session = {
  id: string;
  created_at: string;
  viewed_at: string | null;
  started_at: string | null;
  submitted_at: string | null;
  contact_name: string | null;
  contact_email: string | null;
  contact_phone: string | null;
  utm_source: string | null;
  utm_campaign: string | null;
  responses: Record<string, string | string[]>;
};

const QTYPES: { value: Question["type"]; label: string }[] = [
  { value: "short_text", label: "Texto curto" },
  { value: "long_text", label: "Texto longo" },
  { value: "email", label: "E-mail" },
  { value: "phone", label: "Telefone/WhatsApp" },
  { value: "number", label: "Número" },
  { value: "radio", label: "Múltipla escolha (1)" },
  { value: "checkbox", label: "Múltipla escolha (várias)" },
];

export function FormsAdmin() {
  const list = useServerFn(listForms);
  const create = useServerFn(createForm);
  const del = useServerFn(deleteForm);

  const [items, setItems] = useState<FormListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [viewingSessionsFor, setViewingSessionsFor] = useState<FormListItem | null>(null);
  const [newSlug, setNewSlug] = useState("");
  const [newName, setNewName] = useState("");

  const reload = async () => {
    try {
      const r = (await list()) as FormListItem[];
      setItems(r);
    } catch (e) {
      if (isAuthError(e)) {
        await handleAuthErrorOrThrow(e);
        return;
      }
      toast.error(e instanceof Error ? e.message : "Erro ao carregar");
    } finally {
      setLoading(false);
    }
  };


  useEffect(() => {
    void reload();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onCreate = async () => {
    if (!newName.trim() || !newSlug.trim()) return toast.error("Informe nome e slug.");
    try {
      const row = (await create({
        data: { name: newName.trim(), slug: newSlug.trim().toLowerCase() },
      })) as { id: string };
      setNewName("");
      setNewSlug("");
      await reload();
      setEditingId(row.id);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erro ao criar");
    }
  };

  const onDelete = async (id: string) => {
    if (!confirm("Excluir este formulário e todas as respostas?")) return;
    try {
      await del({ data: { id } });
      await reload();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erro ao excluir");
    }
  };

  const copyLink = async (slug: string) => {
    const url = `${window.location.origin}/f/${slug}`;
    await navigator.clipboard.writeText(url);
    toast.success("Link copiado: " + url);
  };

  if (loading) return <div className="text-muted-foreground">Carregando formulários…</div>;

  return (
    <div className="space-y-6">
      <FormMetricsPanel />
      <MetaConversionsPanel />
      <div className="rounded-2xl border border-border bg-card p-5">
        <h3 className="mb-3 text-sm font-black uppercase tracking-wider">
          Criar novo formulário
        </h3>
        <div className="flex flex-wrap gap-2">
          <input
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="Nome (ex: Diagnóstico gratuito)"
            className="flex-1 min-w-[240px] rounded-lg border border-border bg-background px-3 py-2 text-sm"
          />
          <input
            value={newSlug}
            onChange={(e) => setNewSlug(e.target.value.replace(/[^a-z0-9-]/g, "").toLowerCase())}
            placeholder="slug-do-link"
            className="w-56 rounded-lg border border-border bg-background px-3 py-2 text-sm font-mono"
          />
          <button
            onClick={onCreate}
            className="rounded-lg bg-[#3DFF8A] px-4 py-2 text-sm font-bold text-black"
          >
            Criar
          </button>
        </div>
        <p className="mt-2 text-xs text-muted-foreground">
          O link público será <code>/f/&lt;slug&gt;</code>. Depois abra "Editar" para adicionar as perguntas.
        </p>
      </div>

      {items.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-border bg-card p-12 text-center text-muted-foreground">
          Nenhum formulário ainda.
        </div>
      ) : (
        <div className="overflow-x-auto rounded-2xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-muted/40 text-left text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-4 py-3">Formulário</th>
                <th className="px-4 py-3 text-center">Views</th>
                <th className="px-4 py-3 text-center">Starts</th>
                <th className="px-4 py-3 text-center">Leads</th>
                <th className="px-4 py-3 text-center">Conv.</th>
                <th className="px-4 py-3 text-right">Ações</th>
              </tr>
            </thead>
            <tbody>
              {items.map((f) => {
                const conv = f.stats.views ? Math.round((f.stats.submissions / f.stats.views) * 100) : 0;
                return (
                  <tr key={f.id} className="border-t border-border hover:bg-muted/20">
                    <td className="px-4 py-3">
                      <div className="font-semibold">{f.name}</div>
                      <div className="text-xs text-muted-foreground font-mono">/f/{f.slug}</div>
                    </td>
                    <td className="px-4 py-3 text-center font-mono">{f.stats.views}</td>
                    <td className="px-4 py-3 text-center font-mono">{f.stats.starts}</td>
                    <td className="px-4 py-3 text-center font-mono font-bold">{f.stats.submissions}</td>
                    <td className="px-4 py-3 text-center text-xs">{conv}%</td>
                    <td className="px-4 py-3 text-right whitespace-nowrap">
                      <div className="inline-flex items-center gap-2">
                        <button
                          onClick={() => copyLink(f.slug)}
                          className="rounded-md border border-border px-2.5 py-1.5 text-xs font-semibold text-primary hover:bg-muted"
                        >
                          Copiar link
                        </button>
                        <button
                          onClick={() => setViewingSessionsFor(f)}
                          className="rounded-md border border-border px-2.5 py-1.5 text-xs font-semibold hover:bg-muted"
                        >
                          Respostas
                        </button>
                        <button
                          onClick={() => setEditingId(f.id)}
                          className="rounded-md border border-border px-2.5 py-1.5 text-xs font-semibold hover:bg-muted"
                        >
                          Editar
                        </button>
                        <button
                          onClick={() => onDelete(f.id)}
                          title="Excluir formulário"
                          aria-label="Excluir formulário"
                          className="inline-flex items-center gap-1 rounded-md border border-destructive/50 bg-destructive/10 px-2.5 py-1.5 text-xs font-bold text-destructive hover:bg-destructive hover:text-destructive-foreground"
                        >
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/></svg>
                          Excluir
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {editingId && (
        <FormEditor
          id={editingId}
          onClose={() => {
            setEditingId(null);
            void reload();
          }}
        />
      )}
      {viewingSessionsFor && (
        <SessionsModal
          form={viewingSessionsFor}
          onClose={() => setViewingSessionsFor(null)}
        />
      )}
    </div>
  );
}

function FormEditor({ id, onClose }: { id: string; onClose: () => void }) {
  const load = useServerFn(getFormAdmin);
  const save = useServerFn(saveForm);
  const [form, setForm] = useState<FormFull | null>(null);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const r = (await load({ data: { id } })) as { form: FormFull; questions: Question[] };
        setForm(r.form);
        setQuestions(
          r.questions.map((q) => ({
            id: q.id,
            position: q.position,
            type: q.type,
            label: q.label,
            description: q.description ?? "",
            required: q.required,
            options: Array.isArray(q.options) ? q.options : [],
          })),
        );
      } catch (e) {
        toast.error(e instanceof Error ? e.message : "Erro");
      }
    })();
  }, [id, load]);

  if (!form) {
    return (
      <div className="fixed inset-0 z-50 grid place-items-center bg-black/70 p-4">
        <div className="text-white">Carregando…</div>
      </div>
    );
  }

  const setF = <K extends keyof FormFull>(k: K, v: FormFull[K]) =>
    setForm((f) => (f ? { ...f, [k]: v } : f));

  const addQ = () =>
    setQuestions((qs) => [
      ...qs,
      {
        position: qs.length,
        type: "short_text",
        label: "Nova pergunta",
        description: "",
        required: true,
        options: [],
      },
    ]);

  const updQ = (i: number, patch: Partial<Question>) =>
    setQuestions((qs) => qs.map((q, idx) => (idx === i ? { ...q, ...patch } : q)));

  const rmQ = (i: number) => setQuestions((qs) => qs.filter((_, idx) => idx !== i));

  const move = (i: number, dir: -1 | 1) =>
    setQuestions((qs) => {
      const n = [...qs];
      const j = i + dir;
      if (j < 0 || j >= n.length) return qs;
      [n[i], n[j]] = [n[j], n[i]];
      return n;
    });

  const onSave = async () => {
    if (!form) return;
    setSaving(true);
    try {
      await save({
        data: {
          form: { ...form, id },
          questions: questions.map((q, idx) => ({ ...q, position: idx })),
        },
      });
      toast.success("Salvo!");
      onClose();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erro ao salvar");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 grid place-items-center bg-black/70 p-4 overflow-y-auto">
      <div className="my-8 w-full max-w-4xl rounded-2xl border border-border bg-card p-6">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3 border-b border-border pb-4">
          <div>
            <div className="text-xs uppercase text-muted-foreground">Editando</div>
            <div className="text-lg font-black">{form.name}</div>
          </div>
          <div className="flex gap-2">
            <a
              href={`/f/${form.slug}`}
              target="_blank"
              rel="noreferrer"
              className="rounded-lg border border-border px-3 py-2 text-xs font-bold"
            >
              Pré-visualizar ↗
            </a>
            <button
              onClick={onSave}
              disabled={saving}
              className="rounded-lg bg-[#3DFF8A] px-3 py-2 text-xs font-bold text-black disabled:opacity-60"
            >
              {saving ? "Salvando…" : "Salvar"}
            </button>
            <button onClick={onClose} className="rounded-lg border border-border px-3 py-2 text-xs">
              Fechar
            </button>
          </div>
        </div>

        <div className="max-h-[75vh] space-y-6 overflow-y-auto pr-2">
          <section className="grid gap-4 md:grid-cols-2">
            <MiniField label="Nome" value={form.name} onChange={(v) => setF("name", v)} />
            <MiniField
              label="Slug (link público)"
              value={form.slug}
              onChange={(v) => setF("slug", v.replace(/[^a-z0-9-]/g, "").toLowerCase())}
            />
            <div className="md:col-span-2">
              <RichField
                label="Título da tela inicial"
                value={form.welcome_title}
                onChange={(v) => setF("welcome_title", v)}
                highlightColor={form.highlight_color}
              />
            </div>
            <MiniField
              label="Texto do botão inicial"
              value={form.welcome_cta}
              onChange={(v) => setF("welcome_cta", v)}
            />
            <div className="md:col-span-2">
              <RichField
                label="Subtítulo / descrição inicial"
                value={form.welcome_subtitle}
                onChange={(v) => setF("welcome_subtitle", v)}
                textarea
                highlightColor={form.highlight_color}
              />
            </div>
            <div className="md:col-span-2">
              <RichField
                label="Título de agradecimento"
                value={form.thank_you_title}
                onChange={(v) => setF("thank_you_title", v)}
                highlightColor={form.highlight_color}
              />
            </div>
            <div className="md:col-span-2">
              <RichField
                label="Mensagem de agradecimento"
                value={form.thank_you_message}
                onChange={(v) => setF("thank_you_message", v)}
                textarea
                highlightColor={form.highlight_color}
              />
            </div>

            <div className="md:col-span-2 grid grid-cols-2 md:grid-cols-4 gap-3 rounded-xl border border-border bg-background/50 p-4">
              <ColorField label="Cor do botão" value={form.primary_color} onChange={(v) => setF("primary_color", v)} />
              <ColorField label="Fundo da página" value={form.background_color} onChange={(v) => setF("background_color", v)} />
              <ColorField label="Cor do texto" value={form.text_color} onChange={(v) => setF("text_color", v)} />
              <ColorField label="Cor de destaque" value={form.highlight_color} onChange={(v) => setF("highlight_color", v)} />
            </div>

            <div className="md:col-span-2 flex items-center gap-6">
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={form.is_active}
                  onChange={(e) => setF("is_active", e.target.checked)}
                />{" "}
                Ativo
              </label>
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={form.send_to_meta}
                  onChange={(e) => setF("send_to_meta", e.target.checked)}
                />{" "}
                Enviar eventos ao Meta Pixel + CAPI
              </label>
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={form.show_cal}
                  onChange={(e) => setF("show_cal", e.target.checked)}
                />{" "}
                Exibir Cal.com após envio
              </label>
            </div>
          </section>


          <section>
            <div className="mb-3 flex items-center justify-between">
              <h3 className="text-sm font-black uppercase tracking-wider text-primary">
                Perguntas ({questions.length})
              </h3>
              <button
                onClick={addQ}
                className="rounded-lg bg-primary/20 px-3 py-1.5 text-xs font-bold text-primary hover:bg-primary/30"
              >
                + Adicionar pergunta
              </button>
            </div>
            <div className="space-y-3">
              {questions.map((q, i) => (
                <div key={i} className="rounded-xl border border-border bg-background p-4">
                  <div className="mb-3 flex items-center justify-between gap-2">
                    <span className="text-xs font-bold text-muted-foreground">#{i + 1}</span>
                    <div className="flex gap-2">
                      <button onClick={() => move(i, -1)} className="text-xs px-2 py-1 border border-border rounded">
                        ↑
                      </button>
                      <button onClick={() => move(i, 1)} className="text-xs px-2 py-1 border border-border rounded">
                        ↓
                      </button>
                      <button
                        onClick={() => rmQ(i)}
                        className="text-xs px-2 py-1 border border-destructive/40 text-destructive rounded"
                      >
                        Excluir
                      </button>
                    </div>
                  </div>
                  <div className="grid gap-3 md:grid-cols-3">
                    <div className="md:col-span-2">
                      <RichField
                        label="Pergunta"
                        value={q.label}
                        onChange={(v) => updQ(i, { label: v })}
                        highlightColor={form.highlight_color}
                      />
                    </div>
                    <div>
                      <label className="mb-1 block text-xs font-bold uppercase">Tipo</label>
                      <select
                        value={q.type}
                        onChange={(e) => updQ(i, { type: e.target.value as Question["type"] })}
                        className="w-full rounded-lg border border-border bg-card px-2 py-2 text-sm"
                      >
                        {QTYPES.map((t) => (
                          <option key={t.value} value={t.value}>
                            {t.label}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="md:col-span-3">
                      <RichField
                        label="Descrição (opcional)"
                        value={q.description}
                        onChange={(v) => updQ(i, { description: v })}
                        highlightColor={form.highlight_color}
                      />
                    </div>

                    <label className="flex items-center gap-2 text-sm">
                      <input
                        type="checkbox"
                        checked={q.required}
                        onChange={(e) => updQ(i, { required: e.target.checked })}
                      />{" "}
                      Obrigatória
                    </label>
                    {(q.type === "radio" || q.type === "checkbox") && (
                      <div className="md:col-span-3">
                        <label className="mb-1 block text-xs font-bold uppercase">
                          Opções (uma por linha)
                        </label>
                        <textarea
                          rows={4}
                          value={q.options.join("\n")}
                          onChange={(e) =>
                            updQ(i, {
                              options: e.target.value
                                .split("\n")
                                .map((s) => s.trim())
                                .filter(Boolean),
                            })
                          }
                          className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm"
                        />
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}

function MiniField({
  label,
  value,
  onChange,
  textarea,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  textarea?: boolean;
}) {
  return (
    <div>
      <label className="mb-1 block text-xs font-bold uppercase text-muted-foreground">{label}</label>
      {textarea ? (
        <textarea
          rows={3}
          value={value ?? ""}
          onChange={(e) => onChange(e.target.value)}
          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
        />
      ) : (
        <input
          value={value ?? ""}
          onChange={(e) => onChange(e.target.value)}
          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
        />
      )}
    </div>
  );
}

function ColorField({
  label,
  value,
  onChange,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <div>
      <label className="mb-1 block text-[10px] font-bold uppercase text-muted-foreground">
        {label}
      </label>
      <div className="flex items-center gap-2">
        <input
          type="color"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="h-9 w-12 rounded border border-border bg-background cursor-pointer"
        />
        <input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="w-full rounded-lg border border-border bg-background px-2 py-1.5 text-xs font-mono"
        />
      </div>
    </div>
  );
}

function RichField({
  label,
  value,
  onChange,
  textarea,
  highlightColor,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  textarea?: boolean;
  highlightColor?: string;
}) {
  const ref = useRef<HTMLTextAreaElement | HTMLInputElement | null>(null);

  const wrap = (before: string, after: string) => {
    const el = ref.current;
    if (!el) return;
    const start = el.selectionStart ?? value.length;
    const end = el.selectionEnd ?? value.length;
    const sel = value.slice(start, end) || "texto";
    const next = value.slice(0, start) + before + sel + after + value.slice(end);
    onChange(next);
    requestAnimationFrame(() => {
      el.focus();
      const pos = start + before.length + sel.length + after.length;
      el.setSelectionRange(pos, pos);
    });
  };

  const btn =
    "rounded-md border border-border bg-background px-2 py-1 text-xs font-bold hover:bg-muted";

  return (
    <div>
      <label className="mb-1 block text-xs font-bold uppercase text-muted-foreground">
        {label}
      </label>
      <div className="mb-1 flex flex-wrap items-center gap-1">
        <button type="button" onClick={() => wrap("**", "**")} className={btn} title="Negrito">
          <b>B</b>
        </button>
        <button type="button" onClick={() => wrap("*", "*")} className={btn} title="Itálico">
          <i>I</i>
        </button>
        <button
          type="button"
          onClick={() => wrap("==", "==")}
          className={btn}
          title="Palavra destacada"
          style={{ color: highlightColor }}
        >
          <span className="font-black">H</span>
        </button>
        <span className="ml-2 text-[10px] text-muted-foreground">
          Selecione o texto e clique
        </span>
      </div>
      {textarea ? (
        <textarea
          ref={ref as React.RefObject<HTMLTextAreaElement>}
          rows={3}
          value={value ?? ""}
          onChange={(e) => onChange(e.target.value)}
          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
        />
      ) : (
        <input
          ref={ref as React.RefObject<HTMLInputElement>}
          value={value ?? ""}
          onChange={(e) => onChange(e.target.value)}
          className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
        />
      )}
    </div>
  );
}


function SessionsModal({ form, onClose }: { form: FormListItem; onClose: () => void }) {
  const list = useServerFn(listFormSessions);
  const load = useServerFn(getFormAdmin);
  const [sessions, setSessions] = useState<Session[]>([]);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [detail, setDetail] = useState<Session | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const [s, f] = await Promise.all([
          list({ data: { formId: form.id } }) as Promise<Session[]>,
          load({ data: { id: form.id } }) as Promise<{ form: FormFull; questions: Question[] }>,
        ]);
        setSessions(s);
        setQuestions(f.questions);
      } catch (e) {
        toast.error(e instanceof Error ? e.message : "Erro");
      }
    })();
  }, [form.id, list, load]);

  const submitted = sessions.filter((s) => s.submitted_at);

  const exportCsv = () => {
    const headers = [
      "Data",
      "Nome",
      "Email",
      "Telefone",
      "utm_source",
      "utm_campaign",
      ...questions.map((q) => q.label),
    ];
    const rows = submitted.map((s) => [
      s.submitted_at ? new Date(s.submitted_at).toLocaleString("pt-BR") : "",
      s.contact_name ?? "",
      s.contact_email ?? "",
      s.contact_phone ?? "",
      s.utm_source ?? "",
      s.utm_campaign ?? "",
      ...questions.map((q) => {
        const v = s.responses?.[q.id!];
        return Array.isArray(v) ? v.join(", ") : (v ?? "");
      }),
    ]);
    const csv = [headers, ...rows]
      .map((r) => r.map((v) => `"${String(v).replace(/"/g, '""')}"`).join(","))
      .join("\n");
    const blob = new Blob([`\uFEFF${csv}`], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `respostas-${form.slug}-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="fixed inset-0 z-50 grid place-items-center bg-black/70 p-4 overflow-y-auto">
      <div className="my-8 w-full max-w-5xl rounded-2xl border border-border bg-card p-6">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3 border-b border-border pb-4">
          <div>
            <div className="text-xs uppercase text-muted-foreground">Respostas — {form.name}</div>
            <div className="text-sm text-muted-foreground">
              {form.stats.views} views · {form.stats.starts} starts · {submitted.length} enviados
            </div>
          </div>
          <div className="flex gap-2">
            <button
              onClick={exportCsv}
              disabled={!submitted.length}
              className="rounded-lg bg-[#3DFF8A] px-3 py-2 text-xs font-bold text-black disabled:opacity-50"
            >
              Exportar CSV ↓
            </button>
            <button onClick={onClose} className="rounded-lg border border-border px-3 py-2 text-xs">
              Fechar
            </button>
          </div>
        </div>

        {submitted.length === 0 ? (
          <div className="rounded-xl border border-dashed border-border p-8 text-center text-muted-foreground">
            Nenhum envio ainda.
          </div>
        ) : (
          <div className="max-h-[70vh] overflow-y-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/40 text-left text-xs uppercase tracking-wider text-muted-foreground">
                <tr>
                  <th className="px-3 py-2">Data</th>
                  <th className="px-3 py-2">Nome</th>
                  <th className="px-3 py-2">Contato</th>
                  <th className="px-3 py-2">Origem</th>
                  <th className="px-3 py-2"></th>
                </tr>
              </thead>
              <tbody>
                {submitted.map((s) => (
                  <tr key={s.id} className="border-t border-border hover:bg-muted/20">
                    <td className="px-3 py-2 text-xs text-muted-foreground">
                      {s.submitted_at && new Date(s.submitted_at).toLocaleString("pt-BR")}
                    </td>
                    <td className="px-3 py-2 font-semibold">{s.contact_name ?? "—"}</td>
                    <td className="px-3 py-2 text-xs">
                      {s.contact_email && <div>{s.contact_email}</div>}
                      {s.contact_phone && <div className="text-muted-foreground">{s.contact_phone}</div>}
                    </td>
                    <td className="px-3 py-2 text-xs">
                      {s.utm_source ?? "—"}
                      {s.utm_campaign ? ` · ${s.utm_campaign}` : ""}
                    </td>
                    <td className="px-3 py-2 text-right">
                      <button
                        onClick={() => setDetail(s)}
                        className="text-xs font-semibold text-primary hover:underline"
                      >
                        Ver respostas
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {detail && (
          <div className="fixed inset-0 z-[60] grid place-items-center bg-black/80 p-4">
            <div className="w-full max-w-2xl rounded-2xl border border-border bg-card p-6">
              <div className="mb-3 flex items-center justify-between">
                <div className="text-sm font-black">Respostas</div>
                <button onClick={() => setDetail(null)} className="text-xs">
                  Fechar
                </button>
              </div>
              <div className="max-h-[70vh] space-y-3 overflow-y-auto pr-2">
                {questions.map((q) => {
                  const v = detail.responses?.[q.id!];
                  const val = Array.isArray(v) ? v.join(", ") : (v ?? "—");
                  return (
                    <div key={q.id} className="rounded-lg border border-border bg-background p-3">
                      <div className="text-xs font-semibold text-muted-foreground">{q.label}</div>
                      <div className="mt-1 text-sm">{val || "—"}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
