import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { submitLead } from "@/lib/leads.functions";

export function LeadForm({ id }: { id?: string }) {
  const send = useServerFn(submitLead);
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [state, setState] = useState<"idle" | "sending" | "done" | "error">("idle");
  const [err, setErr] = useState("");

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    const digits = phone.replace(/\D/g, "");
    if (name.trim().length < 2) return setErr("Digite seu nome."), setState("error");
    if (digits.length < 10 || digits.length > 13) return setErr("Digite seu WhatsApp com DDD."), setState("error");
    setState("sending");
    try {
      await send({ data: { name, phone } });
      setState("done");
    } catch {
      setErr("Não foi possível enviar. Tente novamente.");
      setState("error");
    }
  }

  if (state === "done")
    return (
      <div id={id} className="rounded-2xl bg-card p-6 text-center text-card-foreground shadow-xl">
        <p className="font-display text-2xl font-bold text-primary">Recebido! 🎉</p>
        <p className="mt-2 text-muted-foreground">Em breve vou te chamar no WhatsApp com a promoção de 7 dias grátis.</p>
      </div>
    );

  const input = "w-full rounded-xl border bg-background px-4 py-3.5 text-base text-foreground outline-none focus:ring-2 focus:ring-ring";
  return (
    <form id={id} onSubmit={onSubmit} className="space-y-3 rounded-2xl bg-card p-5 text-left text-card-foreground shadow-xl">
      <p className="font-bold">Receba seus 7 dias grátis</p>
      <input className={input} placeholder="Seu nome" value={name} onChange={(e) => setName(e.target.value)} maxLength={100} autoComplete="name" aria-label="Nome" />
      <input className={input} placeholder="WhatsApp com DDD" value={phone} onChange={(e) => setPhone(e.target.value)} maxLength={20} inputMode="tel" autoComplete="tel" aria-label="WhatsApp" />
      {state === "error" && <p className="text-sm text-destructive">{err}</p>}
      <button disabled={state === "sending"} className="w-full rounded-full bg-primary px-6 py-4 font-bold text-primary-foreground shadow-lg transition hover:scale-[1.02] disabled:opacity-60">
        {state === "sending" ? "Enviando..." : "Quero meus 7 dias grátis"}
      </button>
      <p className="text-center text-xs text-muted-foreground">Eu te chamo no WhatsApp. Sem compromisso.</p>
    </form>
  );
}
