import React, { useState, useEffect } from 'react';
import { captureCurrentMetaVariables, generateEventId } from '../utils/metaTracker';
import { MetaTrackingData, FormConfig, DEFAULT_FORM_CONFIG } from '../types';
import { Check, ArrowRight, ArrowLeft, Loader2, ShieldCheck, CheckCircle, Building2, Sliders } from 'lucide-react';

interface EnglishTestFormProps {
  onEventSubmitted?: (result: any) => void;
  activeOverrides?: Partial<MetaTrackingData>;
  isEmbeddedMobile?: boolean;
  config?: FormConfig;
  onOpenConfigModal?: () => void;
}

type StepType = 'goal' | 'blocker' | 'contact';

export const EnglishTestForm: React.FC<EnglishTestFormProps> = ({
  onEventSubmitted,
  activeOverrides,
  isEmbeddedMobile = false,
  config = DEFAULT_FORM_CONFIG,
  onOpenConfigModal,
}) => {
  // Compute active steps dynamically based on config
  const activeSteps: StepType[] = [];
  if (config.enableQuestion1) activeSteps.push('goal');
  if (config.enableQuestion2) activeSteps.push('blocker');
  activeSteps.push('contact');

  const [stepIndex, setStepIndex] = useState<number>(0);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [submissionResult, setSubmissionResult] = useState<any>(null);

  const [formData, setFormData] = useState({
    goal: 'business_career',
    blocker: 'traduction_mentale',
    currentLevel: 'B1_intermediaire',
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
  });

  const [metaVars, setMetaVars] = useState<MetaTrackingData>(() =>
    captureCurrentMetaVariables(activeOverrides)
  );

  useEffect(() => {
    setMetaVars(captureCurrentMetaVariables(activeOverrides));
  }, [activeOverrides]);

  // Ensure stepIndex stays within valid bounds when config changes
  useEffect(() => {
    if (stepIndex >= activeSteps.length) {
      setStepIndex(Math.max(0, activeSteps.length - 1));
    }
  }, [activeSteps.length, stepIndex]);

  const currentStep = activeSteps[stepIndex] || 'contact';

  const handleNext = () => {
    setErrorMessage(null);
    if (stepIndex < activeSteps.length - 1) {
      setStepIndex((s) => s + 1);
    }
  };

  const handlePrev = () => {
    setErrorMessage(null);
    if (stepIndex > 0) {
      setStepIndex((s) => s - 1);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage(null);

    // Dynamic field validation according to config
    const { firstName, lastName, email, phone } = config.fields;

    if (firstName.visible && firstName.required && !formData.firstName.trim()) {
      setErrorMessage(`Veuillez renseigner votre ${firstName.label.toLowerCase()}.`);
      return;
    }
    if (lastName.visible && lastName.required && !formData.lastName.trim()) {
      setErrorMessage(`Veuillez renseigner votre ${lastName.label.toLowerCase()}.`);
      return;
    }
    if (email.visible && email.required && !formData.email.trim()) {
      setErrorMessage(`Veuillez renseigner votre ${email.label.toLowerCase()}.`);
      return;
    }
    if (phone.visible && phone.required && !formData.phone.trim()) {
      setErrorMessage(`Veuillez renseigner votre ${phone.label.toLowerCase()}.`);
      return;
    }

    setIsSubmitting(true);
    const eventId = generateEventId();
    const trackingSnapshot = captureCurrentMetaVariables(activeOverrides);

    const payload = {
      eventName: 'Lead',
      eventId,
      userData: {
        firstName: firstName.visible ? formData.firstName.trim() : undefined,
        lastName: lastName.visible ? formData.lastName.trim() : undefined,
        email: email.visible ? formData.email.trim() : undefined,
        phone: phone.visible ? formData.phone.trim() : undefined,
      },
      assessmentData: {
        goal: config.enableQuestion1 ? formData.goal : 'unspecified_direct_flow',
        blocker: config.enableQuestion2 ? formData.blocker : 'unspecified_direct_flow',
        currentLevel: config.enableQuestion2 ? formData.currentLevel : 'unspecified',
      },
      trackingData: trackingSnapshot,
    };

    // Client-side fbq deduplication if browser pixel active
    if (typeof (window as any).fbq === 'function') {
      try {
        (window as any).fbq('track', 'Lead', {
          content_name: 'Test Anglais Gratuit',
        }, { eventID: eventId });
      } catch (err) {
        console.warn('Pixel local error:', err);
      }
    }

    try {
      const response = await fetch('/api/meta-capi', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await response.json();
      if (!response.ok || !data.success) {
        throw new Error(data.error || 'Erreur lors de la transmission CAPI');
      }

      setSubmissionResult({
        ...data,
        trackingSnapshot,
        eventId,
      });

      if (onEventSubmitted) {
        onEventSubmitted(data);
      }
    } catch (err: any) {
      setErrorMessage(err.message || 'Erreur réseau vers le serveur CAPI.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const resetForm = () => {
    setSubmissionResult(null);
    setStepIndex(0);
    setFormData({
      goal: 'business_career',
      blocker: 'traduction_mentale',
      currentLevel: 'B1_intermediaire',
      firstName: '',
      lastName: '',
      email: '',
      phone: '',
    });
  };

  return (
    <div className={`w-full ${isEmbeddedMobile ? 'max-w-[360px]' : 'max-w-md'} mx-auto flex flex-col justify-between`}>
      {/* Top Header with Business Name & Dynamic Progress Bar */}
      {!submissionResult && (
        <div className="mb-4">
          {/* Business Name at Top Left */}
          <div className="flex items-center justify-between gap-2 mb-2.5">
            <div className="flex items-center gap-1.5 truncate">
              <span className="w-2 h-2 rounded-full bg-indigo-500 shrink-0" />
              <span className="font-bold text-white text-xs tracking-tight truncate">
                {config.businessName || 'Apex English Academy'}
              </span>
            </div>

            <div className="flex items-center gap-2 shrink-0">
              {onOpenConfigModal && (
                <button
                  type="button"
                  onClick={onOpenConfigModal}
                  className="text-[10px] text-indigo-400 hover:text-indigo-300 flex items-center gap-1 bg-slate-900 border border-slate-800 px-2 py-0.5 rounded-full transition cursor-pointer"
                  title="Modifier les questions et champs"
                >
                  <Sliders className="w-2.5 h-2.5" />
                  <span>Ajuster</span>
                </button>
              )}
              <span className="font-mono text-slate-400 text-[11px] font-semibold">
                {stepIndex + 1} / {activeSteps.length}
              </span>
            </div>
          </div>

          {/* Subtitle indicator */}
          <div className="flex items-center justify-between text-[11px] text-slate-400 mb-2">
            <span className="flex items-center gap-1.5 text-slate-300">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 inline-block animate-pulse" />
              Évaluation Gratuite &bull; {activeSteps.length === 1 ? '1 min' : activeSteps.length === 2 ? '5 min' : '10 min'}
            </span>
            <span className="text-[10px] text-slate-500 font-mono">
              {currentStep === 'goal' && 'Étape 1 : Objectif'}
              {currentStep === 'blocker' && 'Étape : Frein & Niveau'}
              {currentStep === 'contact' && 'Étape finale : Accès'}
            </span>
          </div>

          {/* Dynamic Segmented Progress Bar */}
          <div
            className="grid gap-1.5"
            style={{
              gridTemplateColumns: `repeat(${activeSteps.length}, minmax(0, 1fr))`,
            }}
          >
            {activeSteps.map((_, idx) => (
              <div
                key={idx}
                className={`h-1.5 rounded-full transition-all duration-300 ${
                  stepIndex >= idx ? 'bg-indigo-500' : 'bg-slate-800'
                }`}
              />
            ))}
          </div>
        </div>
      )}

      {/* Confirmation State */}
      {submissionResult ? (
        <div className="text-center py-6 animate-in fade-in duration-200">
          <div className="w-12 h-12 rounded-full bg-emerald-950/60 border border-emerald-500/30 text-emerald-400 flex items-center justify-center mx-auto mb-3">
            <CheckCircle className="w-6 h-6" />
          </div>
          <h2 className="text-lg font-bold text-white mb-1">Accès envoyé</h2>
          <p className="text-slate-400 text-xs mb-4 max-w-xs mx-auto">
            Votre test d'anglais calibré a été transmis avec succès. L'événement de conversion est logué en SQLite & CAPI.
          </p>

          <div className="bg-slate-950 border border-slate-800 rounded-xl p-3.5 text-left text-[11px] font-mono text-slate-300 space-y-1.5 mb-5">
            <div className="flex justify-between items-center border-b border-slate-900 pb-1">
              <span className="text-slate-400">Statut CAPI :</span>
              <span className="text-emerald-400 font-semibold">{submissionResult.status}</span>
            </div>
            <div className="flex justify-between items-center border-b border-slate-900 pb-1">
              <span className="text-slate-400">EMQ Score :</span>
              <span className="text-amber-400 font-semibold">{submissionResult.emqScore || '8.8'} / 10</span>
            </div>
            <div className="flex justify-between items-center border-b border-slate-900 pb-1">
              <span className="text-slate-400">Stockage SQLite :</span>
              <span className="text-indigo-400 font-semibold">ID #{submissionResult.sqliteId || 'Enregistré'}</span>
            </div>
            <div className="flex justify-between items-center border-b border-slate-900 pb-1">
              <span className="text-slate-400">Event ID :</span>
              <span className="text-slate-400 truncate max-w-[170px]">{submissionResult.eventId}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-slate-400">Meta _fbp :</span>
              <span className="text-slate-400 truncate max-w-[170px]">{submissionResult.trackingSnapshot?.fbp}</span>
            </div>
          </div>

          <button
            type="button"
            onClick={resetForm}
            className="text-xs text-indigo-400 hover:text-indigo-300 font-medium py-2 px-4 transition cursor-pointer"
          >
            Recommencer le test
          </button>
        </div>
      ) : (
        <form onSubmit={handleSubmit} noValidate className="flex flex-col flex-1 justify-between">
          {/* STEP: GOAL (Question 1) */}
          {currentStep === 'goal' && (
            <div className="animate-in fade-in duration-150">
              <div className="mb-4">
                <h1 className="text-lg font-bold text-white tracking-tight">
                  Quel est votre objectif prioritaire ?
                </h1>
                <p className="text-slate-400 text-xs mt-0.5">
                  Calibre le niveau de difficulté initial.
                </p>
              </div>

              <div className="space-y-2 mb-6">
                {[
                  {
                    id: 'business_career',
                    title: 'Carrière & Réunions pro',
                    desc: 'Prendre la parole et négocier sans stress',
                  },
                  {
                    id: 'oral_fluency',
                    title: 'Fluidité & Spontanéité',
                    desc: 'Supprimer la traduction mentale mot à mot',
                  },
                  {
                    id: 'toeic_ielts',
                    title: 'Score Officiel (TOEIC / IELTS)',
                    desc: 'Certification pour diplôme ou expatriation',
                  },
                ].map((item) => (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => setFormData({ ...formData, goal: item.id })}
                    className={`w-full text-left p-3.5 rounded-xl border transition flex items-center justify-between cursor-pointer active:scale-[0.99] ${
                      formData.goal === item.id
                        ? 'border-indigo-500 bg-indigo-950/25 ring-1 ring-indigo-500'
                        : 'border-slate-800 bg-slate-900/60 hover:border-slate-700'
                    }`}
                  >
                    <div>
                      <div className="text-sm font-semibold text-white">{item.title}</div>
                      <div className="text-[11px] text-slate-400 mt-0.5">{item.desc}</div>
                    </div>
                    <div
                      className={`w-4 h-4 rounded-full border flex items-center justify-center shrink-0 ${
                        formData.goal === item.id
                          ? 'border-indigo-500 bg-indigo-500'
                          : 'border-slate-600'
                      }`}
                    >
                      {formData.goal === item.id && (
                        <div className="w-1.5 h-1.5 rounded-full bg-white" />
                      )}
                    </div>
                  </button>
                ))}
              </div>

              <button
                type="button"
                onClick={handleNext}
                className="w-full h-12 rounded-xl bg-white hover:bg-slate-100 text-slate-950 font-semibold text-sm transition active:scale-[0.98] flex items-center justify-center gap-1.5 cursor-pointer shadow-sm"
              >
                <span>Continuer</span>
                <ArrowRight className="w-4 h-4" />
              </button>
            </div>
          )}

          {/* STEP: BLOCKER & LEVEL (Question 2) */}
          {currentStep === 'blocker' && (
            <div className="animate-in fade-in duration-150">
              <div className="mb-4">
                <h2 className="text-lg font-bold text-white tracking-tight">
                  Votre principal frein aujourd'hui ?
                </h2>
                <p className="text-slate-400 text-xs mt-0.5">
                  Analyse vos automatismes neuronaux.
                </p>
              </div>

              <div className="space-y-2 mb-4">
                {[
                  { id: 'traduction_mentale', label: 'Je traduis mot à mot dans ma tête' },
                  { id: 'peur_faute', label: "Peur de faire une faute ou de l'accent" },
                  { id: 'vocabulaire_fige', label: 'Le vocabulaire met trop de temps à venir' },
                  { id: 'debit_rapide', label: 'Perte de fil dès que le débit est rapide' },
                ].map((b) => (
                  <button
                    key={b.id}
                    type="button"
                    onClick={() => setFormData({ ...formData, blocker: b.id })}
                    className={`w-full text-left p-3 rounded-xl border transition flex items-center justify-between cursor-pointer active:scale-[0.99] ${
                      formData.blocker === b.id
                        ? 'border-indigo-500 bg-indigo-950/25 ring-1 ring-indigo-500'
                        : 'border-slate-800 bg-slate-900/60 hover:border-slate-700'
                    }`}
                  >
                    <span className="text-xs font-medium text-slate-200">{b.label}</span>
                    <div
                      className={`w-3.5 h-3.5 rounded-full border flex items-center justify-center shrink-0 ${
                        formData.blocker === b.id
                          ? 'border-indigo-500 bg-indigo-500'
                          : 'border-slate-600'
                      }`}
                    >
                      {formData.blocker === b.id && (
                        <div className="w-1 h-1 rounded-full bg-white" />
                      )}
                    </div>
                  </button>
                ))}
              </div>

              <div className="mb-5">
                <label className="block text-[11px] font-semibold text-slate-400 uppercase tracking-wider mb-1">
                  Niveau estimé
                </label>
                <select
                  value={formData.currentLevel}
                  onChange={(e) => setFormData({ ...formData, currentLevel: e.target.value })}
                  className="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3 text-xs text-white focus:outline-none focus:border-indigo-500"
                >
                  <option value="A1_debutant">Débutant (A1)</option>
                  <option value="A2_faux_debutant">Éléments de base (A2)</option>
                  <option value="B1_intermediaire">Intermédiaire (B1) - Comprends mais bloque à l'oral</option>
                  <option value="B2_autonome">Intermédiaire confirmé (B2) - Manque d'aisance</option>
                  <option value="C1_avance">Avancé (C1) - En quête de finesse pro</option>
                </select>
              </div>

              <div className="flex items-center gap-2">
                {stepIndex > 0 && (
                  <button
                    type="button"
                    onClick={handlePrev}
                    className="w-1/3 h-12 rounded-xl border border-slate-800 text-slate-400 hover:text-white text-xs font-medium transition cursor-pointer"
                  >
                    Retour
                  </button>
                )}
                <button
                  type="button"
                  onClick={handleNext}
                  className={`${stepIndex > 0 ? 'w-2/3' : 'w-full'} h-12 rounded-xl bg-white hover:bg-slate-100 text-slate-950 font-semibold text-sm transition active:scale-[0.98] flex items-center justify-center gap-1 cursor-pointer`}
                >
                  <span>Dernière étape</span>
                  <ArrowRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}

          {/* STEP: CONTACT & SUBMISSION (Last Step) */}
          {currentStep === 'contact' && (
            <div className="animate-in fade-in duration-150">
              <div className="mb-4">
                <h2 className="text-lg font-bold text-white tracking-tight">
                  Accéder à votre test gratuit
                </h2>
                <p className="text-slate-400 text-xs mt-0.5">
                  Recevez immédiatement vos accès sécurisés.
                </p>
              </div>

              <div className="space-y-3 mb-4">
                {/* First Name Field */}
                {config.fields.firstName.visible && (
                  <div>
                    <label className="block text-[11px] font-semibold text-slate-400 uppercase tracking-wider mb-1">
                      {config.fields.firstName.label} {config.fields.firstName.required ? '*' : '(optionnel)'}
                    </label>
                    <input
                      type="text"
                      required={config.fields.firstName.required}
                      placeholder={config.fields.firstName.placeholder}
                      value={formData.firstName}
                      onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
                      className="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500"
                    />
                  </div>
                )}

                {/* Last Name Field */}
                {config.fields.lastName.visible && (
                  <div>
                    <label className="block text-[11px] font-semibold text-slate-400 uppercase tracking-wider mb-1">
                      {config.fields.lastName.label} {config.fields.lastName.required ? '*' : '(optionnel)'}
                    </label>
                    <input
                      type="text"
                      required={config.fields.lastName.required}
                      placeholder={config.fields.lastName.placeholder}
                      value={formData.lastName}
                      onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
                      className="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500"
                    />
                  </div>
                )}

                {/* Email Field */}
                {config.fields.email.visible && (
                  <div>
                    <label className="block text-[11px] font-semibold text-slate-400 uppercase tracking-wider mb-1">
                      {config.fields.email.label} {config.fields.email.required ? '*' : '(optionnel)'}
                    </label>
                    <input
                      type="email"
                      required={config.fields.email.required}
                      placeholder={config.fields.email.placeholder}
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                      className="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500"
                    />
                  </div>
                )}

                {/* Phone Field */}
                {config.fields.phone.visible && (
                  <div>
                    <label className="block text-[11px] font-semibold text-slate-400 uppercase tracking-wider mb-1">
                      {config.fields.phone.label} {config.fields.phone.required ? '*' : '(optionnel)'}
                    </label>
                    <input
                      type="tel"
                      required={config.fields.phone.required}
                      placeholder={config.fields.phone.placeholder}
                      value={formData.phone}
                      onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                      className="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500"
                    />
                  </div>
                )}
              </div>

              {errorMessage && (
                <div className="text-xs text-rose-400 bg-rose-950/40 border border-rose-900/50 rounded-xl p-2.5 mb-3">
                  {errorMessage}
                </div>
              )}

              <div className="flex items-center gap-2 mb-3">
                {stepIndex > 0 && (
                  <button
                    type="button"
                    onClick={handlePrev}
                    disabled={isSubmitting}
                    className="w-1/3 h-12 rounded-xl border border-slate-800 text-slate-400 hover:text-white text-xs font-medium transition cursor-pointer disabled:opacity-50"
                  >
                    Retour
                  </button>
                )}
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className={`${stepIndex > 0 ? 'w-2/3' : 'w-full'} h-12 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-semibold text-sm transition active:scale-[0.98] flex items-center justify-center gap-1.5 cursor-pointer disabled:opacity-50 shadow-md shadow-indigo-600/20`}
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      <span>Envoi & Sauvegarde...</span>
                    </>
                  ) : (
                    <span>Démarrer le test</span>
                  )}
                </button>
              </div>

              <p className="text-[11px] text-slate-500 text-center flex items-center justify-center gap-1">
                <ShieldCheck className="w-3.5 h-3.5 text-slate-400" />
                <span>Chiffré SHA-256 Meta CAPI & SQLite. 100% gratuit.</span>
              </p>
            </div>
          )}
        </form>
      )}
    </div>
  );
};
