import React from 'react';
import { FormConfig } from '../types';
import { Sliders, Eye, EyeOff, Check, Sparkles, Building2, HelpCircle } from 'lucide-react';

interface FormConfigModalProps {
  isOpen: boolean;
  onClose: () => void;
  config: FormConfig;
  onChangeConfig: (newConfig: FormConfig) => void;
}

export const FormConfigModal: React.FC<FormConfigModalProps> = ({
  isOpen,
  onClose,
  config,
  onChangeConfig,
}) => {
  if (!isOpen) return null;

  const handleToggleQuestion1 = () => {
    // Prevent disabling all questions and having zero steps
    onChangeConfig({
      ...config,
      enableQuestion1: !config.enableQuestion1,
    });
  };

  const handleToggleQuestion2 = () => {
    onChangeConfig({
      ...config,
      enableQuestion2: !config.enableQuestion2,
    });
  };

  const handleFieldChange = (
    fieldKey: 'firstName' | 'lastName' | 'email' | 'phone',
    property: 'visible' | 'required',
    value: boolean
  ) => {
    const updated = {
      ...config,
      fields: {
        ...config.fields,
        [fieldKey]: {
          ...config.fields[fieldKey],
          [property]: value,
          // If hiding, also make sure required doesn't block submission
          ...(property === 'visible' && !value ? { required: false } : {}),
          // If making required, must be visible
          ...(property === 'required' && value ? { visible: true } : {}),
        },
      },
    };
    onChangeConfig(updated);
  };

  // Presets
  const applyPreset = (type: 'full' | 'quick_2step' | 'direct_1step' | 'b2b') => {
    if (type === 'full') {
      onChangeConfig({
        ...config,
        enableQuestion1: true,
        enableQuestion2: true,
        fields: {
          firstName: { visible: true, required: true, label: 'Prénom', placeholder: 'Alexandre' },
          lastName: { visible: false, required: false, label: 'Nom de famille', placeholder: 'Dupont' },
          email: { visible: true, required: true, label: 'Email pro ou personnel', placeholder: 'alexandre@domaine.com' },
          phone: { visible: true, required: false, label: 'Numéro de mobile', placeholder: '06 12 34 56 78' },
        },
      });
    } else if (type === 'quick_2step') {
      onChangeConfig({
        ...config,
        enableQuestion1: true,
        enableQuestion2: false,
        fields: {
          firstName: { visible: true, required: true, label: 'Prénom', placeholder: 'Alexandre' },
          lastName: { visible: false, required: false, label: 'Nom de famille', placeholder: 'Dupont' },
          email: { visible: true, required: true, label: 'Email pro ou personnel', placeholder: 'alexandre@domaine.com' },
          phone: { visible: false, required: false, label: 'Numéro de mobile', placeholder: '06 12 34 56 78' },
        },
      });
    } else if (type === 'direct_1step') {
      onChangeConfig({
        ...config,
        enableQuestion1: false,
        enableQuestion2: false,
        fields: {
          firstName: { visible: true, required: true, label: 'Prénom', placeholder: 'Alexandre' },
          lastName: { visible: false, required: false, label: 'Nom de famille', placeholder: 'Dupont' },
          email: { visible: true, required: true, label: 'Email pro ou personnel', placeholder: 'alexandre@domaine.com' },
          phone: { visible: false, required: false, label: 'Numéro de mobile', placeholder: '06 12 34 56 78' },
        },
      });
    } else if (type === 'b2b') {
      onChangeConfig({
        ...config,
        enableQuestion1: true,
        enableQuestion2: true,
        fields: {
          firstName: { visible: true, required: true, label: 'Prénom', placeholder: 'Alexandre' },
          lastName: { visible: true, required: true, label: 'Nom de famille', placeholder: 'Dupont' },
          email: { visible: true, required: true, label: 'Email pro ou personnel', placeholder: 'alexandre@entreprise.fr' },
          phone: { visible: true, required: true, label: 'Numéro de mobile', placeholder: '06 12 34 56 78' },
        },
      });
    }
  };

  // Calculate active step count
  const activeStepsCount =
    (config.enableQuestion1 ? 1 : 0) + (config.enableQuestion2 ? 1 : 0) + 1;

  return (
    <div className="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-2xl max-w-xl w-full p-5 sm:p-6 shadow-2xl space-y-5 max-h-[90vh] overflow-y-auto animate-in fade-in zoom-in-95 duration-150 text-xs">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-slate-800 pb-3.5">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-xl bg-indigo-600/20 border border-indigo-500/40 text-indigo-400 flex items-center justify-center">
              <Sliders className="w-4 h-4" />
            </div>
            <div>
              <h3 className="font-bold text-white text-base">Configuration Dynamique du Formulaire</h3>
              <p className="text-slate-400 text-[11px]">
                Activez/désactivez les questions, adaptez la barre de progression et ajustez les champs de contact.
              </p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="w-7 h-7 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white flex items-center justify-center"
          >
            &times;
          </button>
        </div>

        {/* 1. Nom du Business */}
        <div className="space-y-2 bg-slate-950 p-4 rounded-xl border border-slate-800">
          <label className="flex items-center gap-2 text-xs font-semibold text-white">
            <Building2 className="w-4 h-4 text-indigo-400" />
            <span>Nom de votre entreprise / Marque (en haut à gauche)</span>
          </label>
          <input
            type="text"
            value={config.businessName}
            onChange={(e) => onChangeConfig({ ...config, businessName: e.target.value })}
            placeholder="Apex English Academy"
            className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3.5 py-2 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500 font-medium"
          />
          <p className="text-[11px] text-slate-500">
            S'affiche dans le header de l'application et en haut du formulaire mobile.
          </p>
        </div>

        {/* 2. Questions 1 & 2 (Activation / Désactivation) */}
        <div className="space-y-3 bg-slate-950 p-4 rounded-xl border border-slate-800">
          <div className="flex items-center justify-between">
            <span className="font-semibold text-white text-xs uppercase tracking-wider">
              Étapes de Qualification & Barre de progression
            </span>
            <span className="text-[11px] px-2 py-0.5 rounded-full bg-indigo-950 border border-indigo-800 text-indigo-300 font-mono">
              Total étapes : {activeStepsCount}
            </span>
          </div>

          <div className="space-y-2">
            {/* Question 1 Toggle */}
            <div className="flex items-center justify-between p-3 rounded-xl border border-slate-800 bg-slate-900/80">
              <div>
                <div className="font-semibold text-white text-xs">Question 1 &bull; Objectif prioritaire</div>
                <div className="text-[11px] text-slate-400">
                  Carrière pro, fluidité orale ou certification (micro-engagement sans friction)
                </div>
              </div>
              <button
                type="button"
                onClick={handleToggleQuestion1}
                className={`px-3 py-1.5 rounded-lg font-semibold text-xs transition cursor-pointer ${
                  config.enableQuestion1
                    ? 'bg-emerald-950 border border-emerald-700/60 text-emerald-400'
                    : 'bg-slate-800 border border-slate-700 text-slate-400'
                }`}
              >
                {config.enableQuestion1 ? 'Activée' : 'Désactivée'}
              </button>
            </div>

            {/* Question 2 Toggle */}
            <div className="flex items-center justify-between p-3 rounded-xl border border-slate-800 bg-slate-900/80">
              <div>
                <div className="font-semibold text-white text-xs">Question 2 &bull; Frein mental & Niveau</div>
                <div className="text-[11px] text-slate-400">
                  Traduction mentale, peur de la faute + sélection du niveau A1 à C1
                </div>
              </div>
              <button
                type="button"
                onClick={handleToggleQuestion2}
                className={`px-3 py-1.5 rounded-lg font-semibold text-xs transition cursor-pointer ${
                  config.enableQuestion2
                    ? 'bg-emerald-950 border border-emerald-700/60 text-emerald-400'
                    : 'bg-slate-800 border border-slate-700 text-slate-400'
                }`}
              >
                {config.enableQuestion2 ? 'Activée' : 'Désactivée'}
              </button>
            </div>
          </div>
          <p className="text-[11px] text-slate-500">
            La barre de progression en segments s'ajuste immédiatement au nombre d'étapes actives.
          </p>
        </div>

        {/* 3. Champs de Contact (Dernière étape) */}
        <div className="space-y-3 bg-slate-950 p-4 rounded-xl border border-slate-800">
          <div className="flex items-center justify-between">
            <span className="font-semibold text-white text-xs uppercase tracking-wider">
              Champs de la Dernière Étape (Coordonnées)
            </span>
            <span className="text-[11px] text-slate-400">Rendre visible / masqué / optionnel</span>
          </div>

          <div className="space-y-2">
            {[
              { key: 'firstName', name: 'Prénom', tip: 'Indispensable pour personnalisation et score EMQ Meta' },
              { key: 'lastName', name: 'Nom de famille', tip: 'Optionnel en B2C, pertinent en B2B' },
              { key: 'email', name: 'Email', tip: 'Clé primaire de contact et de matching CAPI' },
              { key: 'phone', name: 'Téléphone', tip: 'Pour rappel commercial ou SMS de notification' },
            ].map((f) => {
              const fieldKey = f.key as 'firstName' | 'lastName' | 'email' | 'phone';
              const setting = config.fields[fieldKey];

              return (
                <div
                  key={f.key}
                  className="p-2.5 sm:p-3 rounded-xl border border-slate-800 bg-slate-900/80 flex flex-wrap items-center justify-between gap-2"
                >
                  <div>
                    <div className="font-semibold text-white text-xs">{f.name}</div>
                    <div className="text-[10px] text-slate-400">{f.tip}</div>
                  </div>

                  <div className="flex items-center gap-1.5">
                    {/* Visibility Toggle */}
                    <button
                      type="button"
                      onClick={() => handleFieldChange(fieldKey, 'visible', !setting.visible)}
                      className={`flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] font-medium transition cursor-pointer ${
                        setting.visible
                          ? 'bg-slate-800 text-white border border-slate-700'
                          : 'bg-slate-950 text-slate-500 border border-slate-900'
                      }`}
                      title={setting.visible ? 'Champ visible' : 'Champ masqué'}
                    >
                      {setting.visible ? <Eye className="w-3 h-3 text-indigo-400" /> : <EyeOff className="w-3 h-3" />}
                      <span>{setting.visible ? 'Visible' : 'Masqué'}</span>
                    </button>

                    {/* Required / Optional Toggle (only if visible) */}
                    {setting.visible && (
                      <button
                        type="button"
                        onClick={() => handleFieldChange(fieldKey, 'required', !setting.required)}
                        className={`px-2.5 py-1 rounded-lg text-[11px] font-medium transition cursor-pointer ${
                          setting.required
                            ? 'bg-indigo-950 border border-indigo-700 text-indigo-300'
                            : 'bg-slate-800 text-slate-400 border border-slate-700'
                        }`}
                      >
                        {setting.required ? 'Obligatoire *' : 'Optionnel'}
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* 4. Préréglages Rapides (Presets) */}
        <div className="space-y-2">
          <span className="text-[11px] text-slate-400 font-semibold uppercase tracking-wider block">
            Modèles Prêts à l'emploi
          </span>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
            <button
              type="button"
              onClick={() => applyPreset('full')}
              className="p-2.5 rounded-xl border border-slate-800 bg-slate-950 hover:border-slate-700 text-left transition"
            >
              <div className="font-semibold text-white text-xs">Complet 3 étapes</div>
              <div className="text-[10px] text-slate-500">Objectif + Frein + Contact</div>
            </button>
            <button
              type="button"
              onClick={() => applyPreset('quick_2step')}
              className="p-2.5 rounded-xl border border-slate-800 bg-slate-950 hover:border-slate-700 text-left transition"
            >
              <div className="font-semibold text-white text-xs">Express 2 étapes</div>
              <div className="text-[10px] text-slate-500">Objectif + Contact</div>
            </button>
            <button
              type="button"
              onClick={() => applyPreset('direct_1step')}
              className="p-2.5 rounded-xl border border-slate-800 bg-slate-950 hover:border-slate-700 text-left transition"
            >
              <div className="font-semibold text-white text-xs">Direct 1 étape</div>
              <div className="text-[10px] text-slate-500">Formulaire contact pur</div>
            </button>
            <button
              type="button"
              onClick={() => applyPreset('b2b')}
              className="p-2.5 rounded-xl border border-slate-800 bg-slate-950 hover:border-slate-700 text-left transition"
            >
              <div className="font-semibold text-white text-xs">B2B Qualifié</div>
              <div className="text-[10px] text-slate-500">Nom + Phone obligatoire</div>
            </button>
          </div>
        </div>

        {/* Footer */}
        <div className="flex justify-end pt-2 border-t border-slate-800">
          <button
            type="button"
            onClick={onClose}
            className="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-semibold text-xs transition active:scale-[0.98] shadow-sm"
          >
            Appliquer au formulaire
          </button>
        </div>
      </div>
    </div>
  );
};
