'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { crearLead } from '@/app/solicitud/actions';

type FormData = {
  name: string;
  email: string;
  phone: string;
};

type FormErrors = Partial<Record<keyof FormData, string>>;
type SubmitStatus = 'idle' | 'loading' | 'success' | 'error';

const initialData: FormData = {
  name: '',
  email: '',
  phone: '',
};

const initialConsents = {
  privacy: false,
  contracting: false,
};

function validateForm(data: FormData): FormErrors {
  const errors: FormErrors = {};
  if (!data.name.trim()) errors.name = 'El nombre es obligatorio';
  if (!data.email.trim()) {
    errors.email = 'El email es obligatorio';
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
    errors.email = 'Introduce un email válido';
  }
  if (!data.phone.trim()) {
    errors.phone = 'El teléfono es obligatorio';
  } else if (!/^[+\d\s\-().]{7,20}$/.test(data.phone)) {
    errors.phone = 'Introduce un teléfono válido';
  }
  return errors;
}

function LeadForm({ slug }: { slug: string }) {
  const router = useRouter();
  const [formData, setFormData] = useState<FormData>(initialData);
  const [consents, setConsents] = useState(initialConsents);
  const [errors, setErrors] = useState<FormErrors>({});
  const [touched, setTouched] = useState<Partial<Record<keyof FormData, boolean>>>({});
  const [status, setStatus] = useState<SubmitStatus>('idle');
  const [submitError, setSubmitError] = useState<string | null>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    if (touched[name as keyof FormData]) {
      const newErrors = validateForm({ ...formData, [name]: value });
      setErrors((prev) => ({ ...prev, [name]: newErrors[name as keyof FormData] }));
    }
  };

  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    const { name } = e.target;
    setTouched((prev) => ({ ...prev, [name]: true }));
    const newErrors = validateForm(formData);
    setErrors((prev) => ({ ...prev, [name]: newErrors[name as keyof FormData] }));
  };

  const consentsGranted = consents.privacy && consents.contracting;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setTouched({ name: true, email: true, phone: true });
    const validationErrors = validateForm(formData);
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      return;
    }
    if (!consentsGranted) return;

    setStatus('loading');
    setSubmitError(null);
    const result = await crearLead(slug, {
      nombre: formData.name,
      email: formData.email,
      telefono: formData.phone,
      consentPrivacidad: consents.privacy,
      consentContratacion: consents.contracting,
    });
    if (!result.ok) {
      setStatus('error');
      setSubmitError(result.error);
      return;
    }
    router.push(`/solicitud/${result.leadId}`);
  };

  const handleReset = () => {
    setStatus('idle');
    setFormData(initialData);
    setConsents(initialConsents);
    setErrors({});
    setTouched({});
  };

  if (status === 'success') {
    return (
      <div
        className="flex flex-col items-center justify-center text-center gap-4 py-10 px-4 animate-scaleIn"
        role="alert"
        aria-live="polite"
      >
        <div
          className="w-16 h-16 rounded-full flex items-center justify-center mb-2"
          style={{ backgroundColor: 'var(--brand, #0a0a0a)', color: 'var(--brand-contrast, #fff)' }}
        >
          <svg width="28" height="28" viewBox="0 0 32 32" fill="none" aria-hidden="true">
            <path
              d="M6 16l7 7L26 9"
              stroke="currentColor"
              strokeWidth="3"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>
        <h3 className="text-xl font-extrabold tracking-tight text-black">
          ¡Te llamamos enseguida!
        </h3>
        <p className="text-sm text-gray-600 max-w-[300px] leading-relaxed">
          En menos de 2 minutos te llamamos al teléfono que nos has dejado.
          Tendrás el render y el presupuesto en tu WhatsApp.
        </p>
        <button
          className="text-sm font-semibold text-black underline underline-offset-2 hover:no-underline mt-2"
          onClick={handleReset}
        >
          Pedir otro presupuesto
        </button>
      </div>
    );
  }

  return (
    <form
      className="flex flex-col gap-4"
      onSubmit={handleSubmit}
      noValidate
      aria-label="Formulario de captación de lead"
    >
      {/* Name + Email */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="flex flex-col gap-2">
          <label htmlFor="lead-name" className="text-sm font-semibold text-dark">
            Nombre <span className="text-error">*</span>
          </label>
          <input
            id="lead-name"
            name="name"
            type="text"
            className={`w-full px-4 py-3 text-base font-sans text-dark bg-white border-[1.5px] rounded-lg transition-all duration-150 outline-none placeholder:text-gray-400 focus:border-black focus:shadow-[0_0_0_3px_rgba(0,0,0,0.06)] ${errors.name && touched.name
              ? 'border-error shadow-[0_0_0_3px_rgba(255,59,59,0.08)]'
              : 'border-gray-200'
              }`}
            placeholder="Juan García"
            value={formData.name}
            onChange={handleChange}
            onBlur={handleBlur}
            autoComplete="name"
            required
            aria-required="true"
            aria-describedby={errors.name && touched.name ? 'lead-name-error' : undefined}
            aria-invalid={!!(errors.name && touched.name)}
          />
          {errors.name && touched.name && (
            <span id="lead-name-error" className="text-xs text-error font-medium" role="alert">
              {errors.name}
            </span>
          )}
        </div>

        <div className="flex flex-col gap-2">
          <label htmlFor="lead-email" className="text-sm font-semibold text-dark">
            Email <span className="text-error">*</span>
          </label>
          <input
            id="lead-email"
            name="email"
            type="email"
            className={`w-full px-4 py-3 text-base font-sans text-dark bg-white border-[1.5px] rounded-lg transition-all duration-150 outline-none placeholder:text-gray-400 focus:border-black focus:shadow-[0_0_0_3px_rgba(0,0,0,0.06)] ${errors.email && touched.email
              ? 'border-error shadow-[0_0_0_3px_rgba(255,59,59,0.08)]'
              : 'border-gray-200'
              }`}
            placeholder="juan@email.com"
            value={formData.email}
            onChange={handleChange}
            onBlur={handleBlur}
            autoComplete="email"
            required
            aria-required="true"
            aria-describedby={errors.email && touched.email ? 'lead-email-error' : undefined}
            aria-invalid={!!(errors.email && touched.email)}
          />
          {errors.email && touched.email && (
            <span id="lead-email-error" className="text-xs text-error font-medium" role="alert">
              {errors.email}
            </span>
          )}
        </div>
      </div>

      {/* Phone */}
      <div className="flex flex-col gap-2">
        <label htmlFor="lead-phone" className="text-sm font-semibold text-dark">
          Teléfono <span className="text-error">*</span>
        </label>
        <input
          id="lead-phone"
          name="phone"
          type="tel"
          className={`w-full px-4 py-3 text-base font-sans text-dark bg-white border-[1.5px] rounded-lg transition-all duration-150 outline-none placeholder:text-gray-400 focus:border-black focus:shadow-[0_0_0_3px_rgba(0,0,0,0.06)] ${errors.phone && touched.phone
            ? 'border-error shadow-[0_0_0_3px_rgba(255,59,59,0.08)]'
            : 'border-gray-200'
            }`}
          placeholder="+34 612 345 678"
          value={formData.phone}
          onChange={handleChange}
          onBlur={handleBlur}
          autoComplete="tel"
          inputMode="tel"
          required
          aria-required="true"
          aria-describedby={errors.phone && touched.phone ? 'lead-phone-error' : undefined}
          aria-invalid={!!(errors.phone && touched.phone)}
        />
        {errors.phone && touched.phone && (
          <span id="lead-phone-error" className="text-xs text-error font-medium" role="alert">
            {errors.phone}
          </span>
        )}
      </div>

      {/* Consents */}
      <fieldset className="flex flex-col gap-2.5 mt-1 pt-4 border-t border-gray-100">
        <legend className="sr-only">Consentimientos</legend>

        <label
          htmlFor="lead-consent-privacy"
          className="flex items-start gap-2.5 cursor-pointer text-xs text-gray-600 leading-relaxed"
        >
          <input
            id="lead-consent-privacy"
            type="checkbox"
            checked={consents.privacy}
            onChange={(e) => setConsents((c) => ({ ...c, privacy: e.target.checked }))}
            className="mt-0.5 w-4 h-4 accent-black shrink-0 cursor-pointer"
            required
            aria-required="true"
          />
          <span>
            He leído y acepto la{' '}
            <a href="#" className="text-black underline underline-offset-2 hover:no-underline">
              política de privacidad
            </a>
            .
          </span>
        </label>

        <label
          htmlFor="lead-consent-contracting"
          className="flex items-start gap-2.5 cursor-pointer text-xs text-gray-600 leading-relaxed"
        >
          <input
            id="lead-consent-contracting"
            type="checkbox"
            checked={consents.contracting}
            onChange={(e) => setConsents((c) => ({ ...c, contracting: e.target.checked }))}
            className="mt-0.5 w-4 h-4 accent-black shrink-0 cursor-pointer"
            required
            aria-required="true"
          />
          <span>
            He leído y acepto las{' '}
            <a href="#" className="text-black underline underline-offset-2 hover:no-underline">
              condiciones de contratación
            </a>
            .
          </span>
        </label>
      </fieldset>

      {submitError && (
        <p className="text-xs text-error font-medium" role="alert">
          {submitError}
        </p>
      )}

      {/* Submit */}
      <button
        type="submit"
        className="btn btn-brand w-full justify-center mt-1 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none"
        disabled={status === 'loading' || !consentsGranted}
        aria-busy={status === 'loading'}
        aria-disabled={status === 'loading' || !consentsGranted}
      >
        {status === 'loading' ? (
          <>
            <span
              className="w-[18px] h-[18px] border-2 border-white/30 border-t-white rounded-full animate-[spin_0.7s_linear_infinite] shrink-0"
              aria-hidden="true"
            />
            Enviando...
          </>
        ) : (
          <>
            Pedir presupuesto
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path
                d="M2 8h12M10 4l4 4-4 4"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </>
        )}
      </button>
    </form>
  );
}

export default function Hero({ slug }: { slug: string }) {
  const heroRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('opacity-100', 'translate-y-0');
            entry.target.classList.remove('opacity-0', 'translate-y-6');
          }
        });
      },
      { threshold: 0.1 }
    );
    const elements = heroRef.current?.querySelectorAll('.reveal');
    elements?.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  return (
    <section className="bg-white overflow-hidden" id="hero" ref={heroRef} aria-label="Sección principal">
      <div className="container pt-12 md:pt-24 pb-8">

        {/* Grid 2 columnas */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-10 md:gap-16 items-start">

          {/* Columna izquierda — textos */}
          <div className="flex flex-col gap-6">
            <h1 className="reveal opacity-0 translate-y-6 transition-all duration-700 ease-out text-[clamp(2.25rem,5vw,4rem)] font-black tracking-[-0.04em] leading-[1.05] text-black">
              Tu reforma,
              <br />
              <em className="italic font-black">presupuestada</em>
              <br />
              en 5 minutos.
            </h1>

            <p className="reveal opacity-0 translate-y-6 transition-all duration-700 ease-out delay-100 text-base sm:text-lg text-gray-500 leading-relaxed max-w-md">
              Deja tu teléfono, sube una foto de tu cocina o baño y te llamamos desde tu provincia en menos de 2 minutos. Al colgar recibirás por WhatsApp el render de tu reforma + presupuesto desglosado.
            </p>

            {/* CTAs */}
            <div className="reveal opacity-0 translate-y-6 transition-all duration-700 ease-out delay-200 flex flex-col sm:flex-row gap-3">
              <button
                className="btn btn-brand btn-lg w-full sm:w-auto"
                onClick={() => document.querySelector('#contact')?.scrollIntoView({ behavior: 'smooth' })}
              >
                Calcular mi reforma gratis
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                  <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </button>
              <button
                className="btn btn-secondary btn-lg w-full sm:w-auto"
                onClick={() => document.querySelector('#ver-reforma')?.scrollIntoView({ behavior: 'smooth' })}
              >
                Ver una reforma
              </button>
            </div>
          </div>

          {/* Columna derecha — formulario */}
          <div className="reveal opacity-0 translate-y-6 transition-all duration-700 ease-out delay-150 border border-gray-100 rounded-xl p-6 md:p-8 bg-white shadow-sm">
            <div className="mb-5 md:mb-6">
              <h2 className="text-xl font-black tracking-tight text-black">Pide tu presupuesto</h2>
              <p className="text-sm text-gray-400 mt-1">En menos de 2 minutos te llamamos · Render por WhatsApp</p>
            </div>
            <LeadForm slug={slug} />
          </div>

        </div>

        <hr className="border-gray-300 mt-12 md:mt-16 mb-8" />

        {/* Servicios */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-8 sm:gap-6 lg:gap-8 justify-center">
          {[
            {
              icon: (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              ),
              title: 'Reformas Integrales',
              description: 'Gestionamos tu reforma de principio a fin con un objetivo claro: cumplir plazos y superar expectativas.',
            },
            {
              icon: (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <polyline points="9 22 9 12 15 12 15 22" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              ),
              title: 'Reformas de Cocinas',
              description: 'Transforma tu cocina en el espacio que siempre quisiste. Materiales de calidad, diseño a tu medida.',
            },
            {
              icon: (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <path d="M4 12h16M4 12a2 2 0 01-2-2V6a2 2 0 012-2h16a2 2 0 012 2v4a2 2 0 01-2 2M4 12v6a2 2 0 002 2h12a2 2 0 002-2v-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              ),
              title: 'Reformas de Baños',
              description: 'El baño es el espacio más personal del hogar. Te ayudamos a conseguir el resultado que mereces.',
            },
          ].map(({ icon, title, description }) => (
            <div key={title} className="flex flex-col gap-4 items-center text-center">
              <div
                className="w-12 h-12 rounded-full flex items-center justify-center"
                style={{ backgroundColor: 'var(--brand, #0a0a0a)', color: 'var(--brand-contrast, #fff)' }}
              >
                {icon}
              </div>
              <h3 className="text-lg font-black tracking-tight text-black">{title}</h3>
              <p className="text-gray-400 leading-relaxed text-sm max-w-[280px]">{description}</p>
            </div>
          ))}
        </div>

      </div>
    </section>
  );
}
