import { useState } from 'react';
import { QuoteInputSchema, ContactInputSchema } from '@/lib/quote/schema';
import { pushEvent, readUtms } from '@/lib/tracking/dataLayer';

interface HeroProduct {
  id: string;
  name: string;
  sku: string | null;
}
interface Props {
  products: HeroProduct[];
}

/**
 * Cotizador rápido del home: autocontenido. Captura producto + m² + CP +
 * contacto y, al enviar, crea los registros en el CRM y manda a /gracias.
 * NO redirige a otro cotizador.
 */
export default function HeroQuoteForm({ products }: Props) {
  const [productId, setProductId] = useState(products[0]?.id ?? '');
  const [m2, setM2] = useState('');
  const [cp, setCp] = useState('');
  const [fullName, setFullName] = useState('');
  const [whatsapp, setWhatsapp] = useState('');
  const [email, setEmail] = useState('');

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);

  const selected = products.find((p) => p.id === productId);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setServerError(null);

    const quoteParsed = QuoteInputSchema.safeParse({
      productId,
      squareMeters: Number(m2),
      postalCode: cp,
      useCase: 'gimnasio_comercial',
    });
    const contactParsed = ContactInputSchema.safeParse({
      fullName,
      whatsapp,
      email,
    });

    const errs: Record<string, string> = {};
    if (!quoteParsed.success) for (const i of quoteParsed.error.issues) errs[i.path.join('.')] = i.message;
    if (!contactParsed.success) for (const i of contactParsed.error.issues) errs[i.path.join('.')] = i.message;
    if (Object.keys(errs).length) {
      setErrors(errs);
      return;
    }
    setErrors({});
    setLoading(true);
    try {
      pushEvent({ event: 'quote_start', source: 'home' });
      const res = await fetch('/api/quote/create', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          contact: { fullName, whatsapp, email },
          quoteInput: { productId, squareMeters: Number(m2), postalCode: cp, useCase: 'gimnasio_comercial' },
          intent: 'levantar_orden',
          tracking: readUtms(),
        }),
      });
      const json = await res.json();
      if (!json.ok) {
        setServerError(json.error || 'No se pudo enviar tu cotización.');
        return;
      }
      const { quoteId, opportunityId, nextUrl } = json.data;
      pushEvent({ event: 'generate_lead', quote_id: quoteId, opportunity_id: opportunityId, value: 0, intent: 'levantar_orden' });
      window.location.href = nextUrl || `/gracias/${quoteId}`;
    } catch {
      setServerError('Error de red. Intenta de nuevo.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <div className="field">
        <label htmlFor="qq-prod">Producto</label>
        <select className="select" id="qq-prod" value={productId} onChange={(e) => setProductId(e.target.value)}>
          {products.map((p) => (
            <option key={p.id} value={p.id}>{p.name}</option>
          ))}
        </select>
      </div>
      <div className="mini-row">
        <div className="field" style={{ margin: 0 }}>
          <label htmlFor="qq-m2">Metros²</label>
          <input className="input" id="qq-m2" inputMode="decimal" placeholder="45" value={m2} onChange={(e) => setM2(e.target.value)} />
          {errors.squareMeters && <span className="field-error">{errors.squareMeters}</span>}
        </div>
        <div className="field" style={{ margin: 0 }}>
          <label htmlFor="qq-cp">Código postal</label>
          <input className="input" id="qq-cp" inputMode="numeric" maxLength={5} placeholder="11590" value={cp} onChange={(e) => setCp(e.target.value.replace(/\D/g, ''))} />
          {errors.postalCode && <span className="field-error">{errors.postalCode}</span>}
        </div>
      </div>
      <div className="field" style={{ marginTop: 18 }}>
        <label htmlFor="qq-name">Nombre</label>
        <input className="input" id="qq-name" placeholder="Tu nombre" autoComplete="name" value={fullName} onChange={(e) => setFullName(e.target.value)} />
        {errors.fullName && <span className="field-error">{errors.fullName}</span>}
      </div>
      <div className="mini-row">
        <div className="field" style={{ margin: 0 }}>
          <label htmlFor="qq-wa">WhatsApp</label>
          <input className="input" id="qq-wa" inputMode="tel" placeholder="55 1234 5678" autoComplete="tel" value={whatsapp} onChange={(e) => setWhatsapp(e.target.value)} />
          {errors.whatsapp && <span className="field-error">{errors.whatsapp}</span>}
        </div>
        <div className="field" style={{ margin: 0 }}>
          <label htmlFor="qq-mail">Correo</label>
          <input className="input" id="qq-mail" inputMode="email" placeholder="correo@dominio.com" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          {errors.email && <span className="field-error">{errors.email}</span>}
        </div>
      </div>
      {serverError && <p className="field-error" style={{ marginTop: 10 }}>{serverError}</p>}
      <button className="btn btn-primary btn-block" type="submit" disabled={loading} style={{ marginTop: 18 }}>
        {loading ? 'Enviando…' : 'Cotizar y enviar →'}
      </button>
    </form>
  );
}
