"use client";

import { FormEvent, useMemo, useState } from "react";
import { ArrowRight, Check, LoaderCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { dataLayerExperimentAttribution, leadExperimentAttribution } from "@/lib/experiments";
import { useExperiment } from "@/app/components/Experimentation";
import { pushAnalyticsEvent } from "@/app/components/InteractiveBlocks";

const segments = [
  ["empresarios", "Empresário ou gestor"],
  ["comerciais", "Comercial ou profissional autónomo"],
  ["transicao", "Profissional em transição"],
  ["autolideranca", "Autoliderança e consistência"],
  ["empresas-rh", "Empresa ou Recursos Humanos"],
] as const;

export function LeadForm() {
  const [state, setState] = useState<"idle" | "sending" | "success" | "error">("idle");
  const [message, setMessage] = useState("");
  const [whatsapp, setWhatsapp] = useState(false);
  const { assignment } = useExperiment();
  const tracking = useMemo(() => {
    if (typeof window === "undefined") return {};
    const query = new URLSearchParams(window.location.search);
    return { source: query.get("utm_source") ?? "", medium: query.get("utm_medium") ?? "", campaign: query.get("utm_campaign") ?? "", content: query.get("utm_content") ?? "", term: query.get("utm_term") ?? "" };
  }, []);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault(); setState("sending"); setMessage("");
    const form = new FormData(event.currentTarget);
    const body = {
      fullName: form.get("fullName"), email: form.get("email"), phone: form.get("phone"), segment: form.get("segment"),
      website: form.get("website"), consentService: form.get("consentService") === "on",
      consentEmailMarketing: form.get("consentEmailMarketing") === "on", consentWhatsapp: form.get("consentWhatsapp") === "on",
      sourcePath: window.location.pathname, creativeId: new URLSearchParams(window.location.search).get("cid") ?? "", utm: tracking,
      ...leadExperimentAttribution(assignment),
    };
    try {
      const response = await fetch("/api/leads", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
      const result = (await response.json()) as { error?: string };
      if (!response.ok) throw new Error(result.error || "Falha no registo.");
      pushAnalyticsEvent({ event: "generate_lead", form_name: "waitlist", page_path: window.location.pathname, ...dataLayerExperimentAttribution(assignment) });
      setState("success");
    } catch (error) { setState("error"); setMessage(error instanceof Error ? error.message : "Não foi possível concluir o registo."); }
  }

  if (state === "success") return <div className="form-success" role="status"><span><Check aria-hidden="true" /></span><div><strong>Entrada confirmada na lista prioritária.</strong><p>Receberá a informação operacional da primeira edição quando data, cidade e condições estiverem confirmadas.</p></div></div>;

  return (
    <form className="lead-form" onSubmit={submit} noValidate>
      <div className="form-grid">
        <label><span>Nome completo</span><Input name="fullName" autoComplete="name" required placeholder="Como devemos tratar-lhe?" /></label>
        <label><span>E-mail</span><Input name="email" type="email" autoComplete="email" required placeholder="nome@empresa.pt" /></label>
        <label><span>Telefone <small>opcional</small></span><Input name="phone" type="tel" autoComplete="tel" placeholder="+351" /></label>
        <label><span>Perfil principal</span><select name="segment" defaultValue="" required><option value="" disabled>Selecione a sua porta de entrada</option>{segments.map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></label>
      </div>
      <div className="hp" aria-hidden="true"><label>Website<Input name="website" tabIndex={-1} autoComplete="off" /></label></div>
      <div className="consents">
        <label><Checkbox name="consentService" required /><span>Li e compreendo que os dados necessários serão tratados para gerir a minha entrada na lista e responder a este pedido. <b>Confirmação obrigatória.</b></span></label>
        <label><Checkbox name="consentEmailMarketing" /><span>Autorizo conteúdos e convites futuros por e-mail. Posso retirar o consentimento a qualquer momento.</span></label>
        <label><Checkbox name="consentWhatsapp" checked={whatsapp} onCheckedChange={(value) => setWhatsapp(value === true)} /><span>Autorizo contacto por WhatsApp. Só será utilizado se indicar o telefone acima.</span></label>
      </div>
      {state === "error" && <p className="form-error" role="alert">{message}</p>}
      <Button className="cta-button" size="lg" disabled={state === "sending"}>{state === "sending" ? <LoaderCircle className="spin" /> : <>Entrar na lista prioritária <ArrowRight /></>}</Button>
      <p className="privacy-note">Sem venda aberta, sem contadores artificiais e sem partilha da sua informação com parceiros comerciais.</p>
    </form>
  );
}
