"use client";

import { useState } from "react";

type Step = "form" | "success";

export default function RegistroForm() {
  const [step, setStep] = useState<Step>("form");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [correlativeNum, setCorrelativeNum] = useState<number | null>(null);
  const [submittedName, setSubmittedName] = useState("");

  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const res = await fetch("/api/stand/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim(), phone: phone.trim(), email: email.trim() }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? "Error al registrarse. Intenta de nuevo.");
        return;
      }
      setCorrelativeNum(data.correlativeNum);
      setSubmittedName(data.name);
      setStep("success");
    } catch {
      setError("Error de conexión. Verifica tu internet e intenta de nuevo.");
    } finally {
      setLoading(false);
    }
  }

  if (step === "success" && correlativeNum !== null) {
    return (
      <div className="bg-[#111827] rounded-2xl border border-[#1f2937] overflow-hidden shadow-2xl">
        <div className="bg-gradient-to-r from-[#7c3aed] to-[#0ea5c6] px-8 py-6 text-center">
          <div className="text-4xl mb-2">🎉</div>
          <h1 className="text-2xl font-black text-white">¡Registro exitoso!</h1>
        </div>
        <div className="px-8 py-8 text-center">
          <p className="text-gray-400 text-base mb-6">
            {submittedName ? (
              <><span className="text-white font-semibold">{submittedName}</span>, tu turno en el stand es:</>
            ) : "Tu turno en el stand es:"}
          </p>
          <div className="bg-[#0f172a] border-2 border-[#0ea5c6] rounded-2xl px-6 py-8 mb-6">
            <p className="text-xs text-gray-500 uppercase tracking-widest mb-2 font-bold">Número de turno</p>
            <p className="text-7xl font-black text-[#0ea5c6] tracking-widest leading-none">
              #{correlativeNum}
            </p>
          </div>
          <div className="bg-[#0f172a] rounded-xl p-4 mb-6 text-left space-y-2">
            <p className="text-sm font-semibold text-white flex items-center gap-2">
              <span>📋</span> ¿Qué hacer ahora?
            </p>
            <ul className="text-sm text-gray-400 space-y-1 pl-6 list-disc">
              <li>Acércate al stand del evento.</li>
              <li>Indica tu número <span className="text-[#0ea5c6] font-bold">#{correlativeNum}</span> al operador.</li>
              <li>Elige el pack que prefieras.</li>
              <li>Paga con la máquina POS.</li>
              <li>Recibirás tus códigos de sorteo al instante.</li>
            </ul>
          </div>
          <p className="text-xs text-gray-600">También te enviamos este número por correo electrónico.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-[#111827] rounded-2xl border border-[#1f2937] overflow-hidden shadow-2xl">
      <div className="bg-gradient-to-r from-[#7c3aed] to-[#0ea5c6] px-8 py-6">
        <h1 className="text-2xl font-black text-white text-center">Registro de Participación</h1>
        <p className="text-white/80 text-sm text-center mt-1">Stand presencial · Concursando con Amor</p>
      </div>
      <div className="px-8 py-8">
        <p className="text-gray-400 text-sm text-center mb-6">
          Completa el formulario para obtener tu número de turno y acércate al stand.
        </p>
        <form onSubmit={handleSubmit} className="space-y-5">
          <div>
            <label className="block text-sm font-semibold text-gray-300 mb-1.5">Nombre completo</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Juan Pérez"
              required
              minLength={2}
              maxLength={80}
              disabled={loading}
              className="w-full bg-[#0f172a] border border-[#374151] rounded-xl px-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-[#0ea5c6] focus:ring-1 focus:ring-[#0ea5c6] transition disabled:opacity-50"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-300 mb-1.5">
              Teléfono <span className="text-gray-500 font-normal">(9 dígitos, sin +56)</span>
            </label>
            <input
              type="tel"
              value={phone}
              onChange={(e) => setPhone(e.target.value.replace(/\D/g, "").slice(0, 9))}
              placeholder="912345678"
              required
              pattern="\d{9}"
              disabled={loading}
              className="w-full bg-[#0f172a] border border-[#374151] rounded-xl px-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-[#0ea5c6] focus:ring-1 focus:ring-[#0ea5c6] transition disabled:opacity-50"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-gray-300 mb-1.5">Correo electrónico</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="correo@ejemplo.com"
              required
              disabled={loading}
              className="w-full bg-[#0f172a] border border-[#374151] rounded-xl px-4 py-3 text-white placeholder-gray-600 focus:outline-none focus:border-[#0ea5c6] focus:ring-1 focus:ring-[#0ea5c6] transition disabled:opacity-50"
            />
          </div>
          {error && (
            <div className="bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-3">
              <p className="text-red-400 text-sm">{error}</p>
            </div>
          )}
          <button
            type="submit"
            disabled={loading}
            className="w-full bg-gradient-to-r from-[#7c3aed] to-[#0ea5c6] text-white font-black text-base py-4 rounded-xl hover:opacity-90 transition disabled:opacity-50 disabled:cursor-not-allowed shadow-lg"
          >
            {loading ? (
              <span className="flex items-center justify-center gap-2">
                <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24" fill="none">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z" />
                </svg>
                Registrando...
              </span>
            ) : "Obtener mi número de turno →"}
          </button>
        </form>
        <p className="text-xs text-gray-600 text-center mt-6">
          Al registrarte recibirás un correo con tu número de turno.
        </p>
      </div>
    </div>
  );
}
