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

interface WizardProduct {
  id: string;
  name: string;
  sku: string | null;
  category: string;
  quote_enabled: boolean;
  price_without_vat_mxn: number | null;
}
interface CalcResult {
  units: number;
  coverageM2: number;
  subtotal: number;
  tax: number;
  total: number;
  shippingEstimate: number | null;
  requiresSpecialistValidation: boolean;
}
interface Props {
  products: WizardProduct[];
  initialProductId?: string;
  initialSquareMeters?: string;
  initialPostalCode?: string;
}

type Intent = 'levantar_orden' | 'hablar_con_especialista';

const peso = new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' });

const USO_OPTIONS = [
  { v: 'gimnasio_comercial', l: 'Gimnasio comercial' },
  { v: 'box_crossfit', l: 'Box / CrossFit' },
  { v: 'estudio', l: 'Estudio / funcional' },
  { v: 'home_gym', l: 'Home gym' },
  { v: 'acustico', l: 'Proyecto / obra (acústico)' },
];

export default function QuoteWizard({
  products,
  initialProductId,
  initialSquareMeters = '',
  initialPostalCode = '',
}: Props) {
  const quotable = useMemo(() => products.filter((p) => p.quote_enabled), [products]);
  const [step, setStep] = useState(1);
  const [productId, setProductId] = useState(initialProductId ?? quotable[0]?.id ?? '');
  const [m2, setM2] = useState(initialSquareMeters);
  const [cp, setCp] = useState(initialPostalCode);
  const [uso, setUso] = useState('gimnasio_comercial');

  const [fullName, setFullName] = useState('');
  const [company, setCompany] = useState('');
  const [whatsapp, setWhatsapp] = useState('');
  const [email, setEmail] = useState('');

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

  const selectedProduct = products.find((p) => p.id === productId);
  const usoLabel = USO_OPTIONS.find((u) => u.v === uso)?.l ?? uso;
  const isAcoustic = selectedProduct?.category === 'acustico_underlayment';

  async function handleCalculate(e: React.FormEvent) {
    e.preventDefault();
    setServerError(null);
    const parsed = QuoteInputSchema.safeParse({
      productId,
      squareMeters: Number(m2),
      postalCode: cp,
      useCase: uso,
    });
    if (!parsed.success) {
      const errs: Record<string, string> = {};
      for (const i of parsed.error.issues) errs[i.path.join('.')] = i.message;
      setErrors(errs);
      return;
    }
    setErrors({});
    setLoading(true);
    try {
      const res = await fetch('/api/quote/calculate', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(parsed.data),
      });
      const json = await res.json();
      if (!json.ok) {
        setServerError(json.error || 'No se pudo calcular la cotización.');
        return;
      }
      const c: CalcResult = json.data;
      setCalc(c);
      pushEvent({
        event: 'quote_calculated',
        product_id: productId,
        product_sku: selectedProduct?.sku ?? null,
        square_meters: parsed.data.squareMeters,
        units: c.units,
        value: c.total,
        currency: 'MXN',
      });
      setStep(2);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch {
      setServerError('Error de red. Intenta de nuevo.');
    } finally {
      setLoading(false);
    }
  }

  async function handleSubmit(intent: Intent) {
    setServerError(null);
    const parsed = ContactInputSchema.safeParse({
      fullName,
      company: company || undefined,
      whatsapp,
      email,
    });
    if (!parsed.success) {
      const errs: Record<string, string> = {};
      for (const i of parsed.error.issues) errs[i.path.join('.')] = i.message;
      setErrors(errs);
      return;
    }
    setErrors({});
    setLoading(true);
    try {
      const res = await fetch('/api/quote/create', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          contact: { fullName, company: company || undefined, whatsapp, email },
          quoteInput: { productId, squareMeters: Number(m2), postalCode: cp, useCase: uso },
          intent,
          tracking: readUtms(),
        }),
      });
      const json = await res.json();
      if (!json.ok) {
        setServerError(json.error || 'No se pudo registrar la cotización.');
        return;
      }
      const { quoteId, opportunityId, nextUrl } = json.data;
      const value = calc?.total ?? 0;
      if (intent === 'levantar_orden') {
        pushEvent({ event: 'generate_lead', quote_id: quoteId, opportunity_id: opportunityId, value, intent });
      } else {
        pushEvent({ event: 'specialist_requested', quote_id: quoteId, opportunity_id: opportunityId, value });
      }
      window.location.href = nextUrl || `/gracias/${quoteId}`;
    } catch {
      setServerError('Error de red. Intenta de nuevo.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      {/* Stepper */}
      <div className="stepper">
        <div className={`dot ${step === 1 ? 'active' : 'done'}`}>
          <span className="ring">{step === 1 ? '1' : '✓'}</span> Tu proyecto
        </div>
        <div className={`bar ${step === 2 ? 'on' : ''}`}></div>
        <div className={`dot ${step === 2 ? 'active' : ''}`}>
          <span className="ring">2</span> Tu estimado
        </div>
      </div>

      {step === 1 && (
        <div className="card pad">
          <div className="progress"><i className="on"></i><i></i></div>
          <div className="step-label">Paso 1 de 2 · Datos del espacio</div>
          <form onSubmit={handleCalculate} noValidate>
            <div className="field">
              <label htmlFor="q-prod">Producto</label>
              <select className="select" id="q-prod" value={productId} onChange={(e) => setProductId(e.target.value)}>
                {quotable.length === 0 && <option value="">Sin productos cotizables</option>}
                {quotable.map((p) => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
              </select>
              {errors.productId && <span className="field-error">{errors.productId}</span>}
            </div>
            <div className="field">
              <label htmlFor="q-m2">Metros cuadrados a cubrir</label>
              <div className="input-affix">
                <input className="input" id="q-m2" inputMode="decimal" placeholder="Ej. 45" value={m2} onChange={(e) => setM2(e.target.value)} />
                <span className="affix">m²</span>
              </div>
              {errors.squareMeters && <span className="field-error">{errors.squareMeters}</span>}
            </div>
            <div className="field">
              <label htmlFor="q-cp">Código postal de entrega</label>
              <input className="input" id="q-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 className="field">
              <label htmlFor="q-uso">Uso del espacio</label>
              <select className="select" id="q-uso" value={uso} onChange={(e) => setUso(e.target.value)}>
                {USO_OPTIONS.map((u) => <option key={u.v} value={u.v}>{u.l}</option>)}
              </select>
            </div>
            {serverError && <p className="field-error">{serverError}</p>}
            <button className="btn btn-primary btn-block btn-lg" type="submit" disabled={loading}>
              {loading ? 'Calculando…' : 'Calcular cotización →'}
            </button>
          </form>
          <p className="muted" style={{ fontSize: '.8rem', textAlign: 'center', marginTop: 14 }}>🔒 Tus datos están seguros. Sin spam.</p>
        </div>
      )}

      {step === 2 && calc && (
        <div className="quote-result sticky">
          <div className="progress"><i className="on"></i><i className="on"></i></div>
          <div className="step-label">Paso 2 de 2 · Tu estimado</div>

          <div className="estimate">
            <div className="est-head">
              <span className="eyebrow" style={{ margin: 0 }}>{selectedProduct?.name}</span>
              <span className="badge badge-quotable">Estimado</span>
            </div>
            <div className="line"><span>Piezas / rollos sugeridos</span><b>{calc.units}</b></div>
            <div className="line"><span>m² estimados cubiertos</span><b>{calc.coverageM2}</b></div>
            <div className="line"><span>Uso del espacio</span><b>{usoLabel}</b></div>
            <div className="line"><span>Subtotal</span><b>{peso.format(calc.subtotal)}</b></div>
            <div className="line"><span>IVA (16%)</span><b>{peso.format(calc.tax)}</b></div>
            <div className="line"><span>Envío (CP {cp})</span><b className="muted">pendiente de confirmar</b></div>
            <div className="total"><span className="muted">Total estimado</span><span className="big">{peso.format(calc.total)}</span></div>

            {isAcoustic && (
              <div className="notice notice--warn">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 9v4M12 17h.01" /><path d="M10.3 3.9L1.8 18a2 2 0 001.7 3h16.9a2 2 0 001.7-3L13.7 3.9a2 2 0 00-3.4 0z" /></svg>
                <span>Los sistemas acústicos GenieMat se cotizan por proyecto. Un especialista validará especificación, capas y bajo piso según tu obra.</span>
              </div>
            )}
            <div className="notice notice--accent">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 16v-4M12 8h.01" /><circle cx="12" cy="12" r="9" /></svg>
              <span>Cotización estimada. Un especialista validará disponibilidad, envío e instalación.</span>
            </div>
          </div>

          <h3 style={{ margin: '24px 0 4px', fontSize: '1.2rem', textTransform: 'uppercase' }}>Tus datos para enviar la cotización</h3>
          <div className="field">
            <label htmlFor="c-nombre">Nombre completo</label>
            <input className="input" id="c-nombre" 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="field">
            <label htmlFor="c-empresa">Empresa (opcional)</label>
            <input className="input" id="c-empresa" placeholder="Tu gimnasio / empresa" autoComplete="organization" value={company} onChange={(e) => setCompany(e.target.value)} />
          </div>
          <div className="field">
            <label htmlFor="c-wa">WhatsApp</label>
            <input className="input" id="c-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">
            <label htmlFor="c-mail">Correo</label>
            <input className="input" id="c-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>

          {serverError && <p className="field-error">{serverError}</p>}

          <div className="quote-result__ctas">
            <button className="btn btn-primary btn-lg" disabled={loading} onClick={() => handleSubmit('levantar_orden')}>
              {loading ? 'Enviando…' : 'Levantar orden'}
            </button>
            <button className="btn btn-secondary btn-lg" disabled={loading} onClick={() => handleSubmit('hablar_con_especialista')}>
              Hablar con especialista
            </button>
          </div>
          <button className="btn-link" style={{ color: 'var(--pf-text-dim)', background: 'none', border: 'none', cursor: 'pointer', marginTop: 6 }} disabled={loading} onClick={() => setStep(1)}>
            ← Modificar datos
          </button>
        </div>
      )}
    </div>
  );
}
