"use client";

import { useEffect, useRef, useState } from 'react';
import { useForm, Controller, type FieldErrors } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { ArrowRight, Check, ChevronDown } from 'lucide-react';
import { toast } from 'sonner';
import { smoothScrollIntoView, prefersReducedMotion } from '@/lib/smoothScroll';
import { submitDiagnosticToHubspot, type HubspotFormConfig } from '@/lib/hubspot';
import { pushFormSubmit } from '@/lib/dataLayer';
import { suggestEmail } from '@/lib/emailSuggest';
import { formatMissingFields, scrollToFirstError } from '@/lib/formErrors';
import { CountrySelect } from './CountrySelect';

import {
  diagnosticSchema,
  diagnosticDefaultValues,
  isBlock1Filled,
  isBlock2Filled,
  enjeux,
  typesRevetement,
  prestations,
  profils,
  fieldLabels,
  type DiagnosticFormValues,
} from '@/lib/diagnosticForm';

import { FormBlock } from './FormBlock';
import { CheckboxCards } from './CheckboxCards';
import { SurfaceInput } from './SurfaceInput';
import { Field, inputClass, type FormTheme } from './Field';
import { PhoneField } from './PhoneField';
import { cn } from '@/lib/utils';
import { TurnstileCaptcha } from '@/components/forms/TurnstileCaptcha';

export const DiagnosticForm = ({
  hubspotForm,
  theme = 'light',
}: { hubspotForm?: HubspotFormConfig; theme?: FormTheme } = {}) => {
  const dark = theme === 'dark';
  const {
    control,
    register,
    handleSubmit,
    watch,
    setValue,
    getValues,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<DiagnosticFormValues>({
    resolver: zodResolver(diagnosticSchema),
    defaultValues: diagnosticDefaultValues as DiagnosticFormValues,
    mode: 'onChange',
  });

  const values = watch();
  // En thème sombre (modale hero), toutes les étapes sont dépliées d'emblée → le bouton
  // « Demander mon devis » est toujours visible. En clair (page /diagnostic), révélation progressive.
  const [revealed, setRevealed] = useState(dark ? 3 : 1);
  const [submitted, setSubmitted] = useState(false);
  const [emailSuggestion, setEmailSuggestion] = useState<string | null>(null);
  const [errorSummary, setErrorSummary] = useState<string | null>(null);
  const [captchaToken, setCaptchaToken] = useState('');
  const prevRevealed = useRef(dark ? 3 : 1);

  const block2Ref = useRef<HTMLDivElement>(null);
  const block3Ref = useRef<HTMLDivElement>(null);
  const successRef = useRef<HTMLDivElement>(null);
  const formRef = useRef<HTMLFormElement>(null);

  // Autofill detection — copie les valeurs remplies par le navigateur dans RHF
  // (les champs sr-only / contrôlés ne déclenchent pas toujours d'event React).
  const syncAutofilledValues = () => {
    const form = formRef.current;
    if (!form) return;
    const fields: (keyof DiagnosticFormValues)[] = [
      'firstName',
      'lastName',
      'company',
      'email',
      'city',
      'postalCode',
    ];
    fields.forEach((name) => {
      const input = form.querySelector<HTMLInputElement>(`[name="${name}"]`);
      if (!input) return;
      const domValue = input.value;
      if (domValue && getValues(name) !== domValue) {
        setValue(name, domValue, { shouldValidate: true, shouldDirty: true });
      }
    });
  };

  // Étape de révélation à partir de l'état du formulaire (désactivée en sombre : tout est déplié)
  useEffect(() => {
    if (dark) return;
    const block1 = isBlock1Filled(values);
    const block2 = block1 && isBlock2Filled(values);
    const target = block2 ? 3 : block1 ? 2 : 1;
    setRevealed((prev) => (target > prev ? target : prev));
  }, [values, dark]);

  // Auto-scroll quand un nouveau bloc apparaît (pas de scroll auto en sombre)
  useEffect(() => {
    if (dark) return;
    if (revealed <= prevRevealed.current) {
      prevRevealed.current = revealed;
      return;
    }
    prevRevealed.current = revealed;
    const map = { 2: block2Ref, 3: block3Ref } as const;
    const targetRef = map[revealed as 2 | 3];
    if (!targetRef?.current) return;
    const timer = setTimeout(() => {
      smoothScrollIntoView(targetRef.current, { offset: 112, duration: 1000 });
    }, 120);
    return () => clearTimeout(timer);
  }, [revealed, dark]);

  const onSubmit = async (data: DiagnosticFormValues) => {
    if (!captchaToken) {
      toast.error('Validez le captcha avant l’envoi.');
      return;
    }
    try {
      await submitDiagnosticToHubspot(data, hubspotForm, captchaToken);
    } catch (err) {
      console.error('[DiagnosticForm] HubSpot submit failed', err);
      toast.error("L'envoi a échoué. Réessayez dans un instant ou contactez-nous directement.");
      return;
    }
    // Envoi confirmé côté HubSpot : on remonte l'event GTM une seule fois.
    pushFormSubmit('form_diagnostic_submit', 'diagnostic');
    setSubmitted(true);
    toast.success('Demande envoyée — un expert Covalba vous rappelle sous 24h.');
    if (!prefersReducedMotion()) {
      setTimeout(() => smoothScrollIntoView(successRef.current, { offset: 112, duration: 900 }), 50);
    }
  };

  const onInvalid = (errs: FieldErrors<DiagnosticFormValues>) => {
    const msg = formatMissingFields(Object.keys(errs), fieldLabels);
    setErrorSummary(msg);
    toast.error(msg, { duration: 8000 });
    window.setTimeout(() => scrollToFirstError(formRef.current), 60);
  };

  const handleReset = () => {
    reset(diagnosticDefaultValues as DiagnosticFormValues);
    setSubmitted(false);
    setRevealed(dark ? 3 : 1);
    setEmailSuggestion(null);
    prevRevealed.current = dark ? 3 : 1;
  };

  const emailReg = register('email');

  if (submitted) {
    return (
      <div
        ref={successRef}
        className={cn(
          'rounded-2xl p-8 lg:p-12',
          dark ? 'bg-[#0b1a2b]/80 border border-white/[0.08] backdrop-blur-xl' : 'bg-white shadow-sm',
        )}
      >
        <div className="flex flex-col items-center text-center py-6">
          <div className={cn('w-16 h-16 rounded-full flex items-center justify-center mb-6', dark ? 'bg-green-500/15' : 'bg-green-100')}>
            <Check className={cn('w-8 h-8', dark ? 'text-green-400' : 'text-green-600')} strokeWidth={2.5} />
          </div>
          <h2
            className={cn('font-satoshi text-2xl lg:text-3xl font-black mb-3', dark ? 'text-white' : 'text-foreground')}
            style={{ letterSpacing: '-0.02em' }}
          >
            Demande envoyée !
          </h2>
          <p className={cn('font-body text-base lg:text-lg leading-relaxed max-w-md', dark ? 'text-white/60' : 'text-foreground/60')}>
            Un expert Covalba analyse votre demande et vous contacte sous{' '}
            <span className={cn('font-semibold', dark ? 'text-white' : 'text-foreground')}>24h ouvrées</span> avec une proposition adaptée.
          </p>
          <button
            type="button"
            onClick={handleReset}
            className={cn(
              'mt-8 text-sm font-body underline underline-offset-4 transition-colors',
              dark ? 'text-white/50 hover:text-white' : 'text-foreground/50 hover:text-foreground',
            )}
          >
            Envoyer une nouvelle demande
          </button>
        </div>
      </div>
    );
  }

  return (
    <div
      className={cn(
        'rounded-2xl overflow-hidden',
        dark ? 'bg-[#0b1a2b]/80 border border-white/[0.08] backdrop-blur-xl' : 'bg-white shadow-sm',
      )}
    >
      <form
        ref={formRef}
        onSubmit={handleSubmit(onSubmit, onInvalid)}
        onAnimationStart={(e) => {
          if (e.animationName === 'onAutoFillStart') {
            setTimeout(syncAutofilledValues, 60);
          }
        }}
        className="p-6 sm:p-8 lg:p-12"
        noValidate
      >
        {/* === BLOCK 1 — Votre besoin === */}
        <FormBlock step={1} title="Votre besoin" subtitle="Pour adapter notre étude" active theme={theme}>
          <Controller
            name="enjeux"
            control={control}
            render={({ field }) => (
              <Field label="Vos enjeux" required error={errors.enjeux?.message as string | undefined} theme={theme}>
                <CheckboxCards
                  options={enjeux}
                  value={field.value || []}
                  onChange={field.onChange}
                  columns="grid-cols-1 sm:grid-cols-2"
                  ariaLabel="Vos enjeux"
                  theme={theme}
                />
              </Field>
            )}
          />

          <div className="mt-8">
            <Controller
              name="typeRevetement"
              control={control}
              render={({ field }) => (
                <Field label="Type de revêtement" hint="Optionnel — plusieurs choix possibles" theme={theme}>
                  <CheckboxCards
                    options={typesRevetement}
                    value={field.value || []}
                    onChange={field.onChange}
                    columns="grid-cols-1 sm:grid-cols-2 lg:grid-cols-3"
                    ariaLabel="Type de revêtement"
                    theme={theme}
                  />
                </Field>
              )}
            />
          </div>

          <div className="mt-8">
            <Controller
              name="superficie"
              control={control}
              render={({ field }) => (
                <Field
                  label="Superficie à traiter"
                  hint="Optionnel — une estimation suffit"
                  error={errors.superficie?.message}
                  theme={theme}
                >
                  <SurfaceInput value={field.value} onChange={field.onChange} theme={theme} />
                </Field>
              )}
            />
          </div>

          <div className="mt-8">
            <Controller
              name="prestation"
              control={control}
              render={({ field }) => (
                <Field label="Prestation souhaitée" hint="Optionnel" theme={theme}>
                  <CheckboxCards
                    options={prestations}
                    value={field.value || []}
                    onChange={field.onChange}
                    columns="grid-cols-1 sm:grid-cols-2"
                    ariaLabel="Prestation souhaitée"
                    theme={theme}
                  />
                </Field>
              )}
            />
          </div>
        </FormBlock>

        {/* === BLOCK 2 — Vous === */}
        <FormBlock
          ref={block2Ref}
          step={2}
          title="Vous"
          subtitle="Pour vous transmettre l'étude"
          active={revealed >= 2}
          theme={theme}
        >
          <Field label="Profil" required error={errors.profil?.message} theme={theme}>
            <div className="relative">
              <select
                {...register('profil')}
                className={`${inputClass(theme)} appearance-none pr-12 cursor-pointer`}
                defaultValue=""
              >
                <option value="" disabled>
                  Veuillez sélectionner
                </option>
                {profils.map((p) => (
                  <option key={p.value} value={p.value}>
                    {p.label}
                  </option>
                ))}
              </select>
              <ChevronDown
                className={cn('pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5', dark ? 'text-white/50' : 'text-foreground/40')}
                strokeWidth={2}
              />
            </div>
          </Field>

          <div className="mt-6 grid sm:grid-cols-2 gap-4">
            <Field label="Prénom" required error={errors.firstName?.message} theme={theme}>
              <input type="text" placeholder="Jean" {...register('firstName')} className={inputClass(theme)} />
            </Field>
            <Field label="Nom" required error={errors.lastName?.message} theme={theme}>
              <input type="text" placeholder="Dupont" {...register('lastName')} className={inputClass(theme)} />
            </Field>
          </div>

          <div className="mt-6">
            <Field label="Nom de l'entreprise" error={errors.company?.message} theme={theme}>
              <input
                type="text"
                placeholder="Nom de l'entreprise"
                {...register('company')}
                className={inputClass(theme)}
              />
            </Field>
          </div>

          <div className="mt-6 grid sm:grid-cols-2 gap-4">
            <Field label="Email professionnel" required error={errors.email?.message} theme={theme}>
              <input
                type="email"
                placeholder="jean.dupont@entreprise.fr"
                {...emailReg}
                onChange={(e) => {
                  emailReg.onChange(e);
                  if (emailSuggestion) setEmailSuggestion(null);
                }}
                onBlur={(e) => {
                  emailReg.onBlur(e);
                  const v = getValues('email');
                  setEmailSuggestion(v ? suggestEmail(v) : null);
                }}
                className={inputClass(theme)}
              />
              {emailSuggestion && (
                <p className={cn('text-xs font-body mt-2', dark ? 'text-white/70' : 'text-foreground/70')}>
                  Vouliez-vous dire{' '}
                  <button
                    type="button"
                    onClick={() => {
                      setValue('email', emailSuggestion, { shouldValidate: true, shouldDirty: true });
                      setEmailSuggestion(null);
                    }}
                    className="font-semibold text-primary underline underline-offset-2"
                  >
                    {emailSuggestion}
                  </button>{' '}
                  ?
                </p>
              )}
            </Field>
            <Field label="Numéro de téléphone" required error={errors.phone?.message} theme={theme}>
              <Controller
                name="phone"
                control={control}
                render={({ field }) => (
                  <PhoneField value={field.value} onChange={field.onChange} onBlur={field.onBlur} theme={theme} />
                )}
              />
            </Field>
          </div>

          <div className="mt-6 grid sm:grid-cols-3 gap-4">
            <Field label="Ville" error={errors.city?.message} theme={theme}>
              <input type="text" placeholder="Paris" {...register('city')} className={inputClass(theme)} />
            </Field>
            <Field label="Code postal" error={errors.postalCode?.message} theme={theme}>
              <input
                type="text"
                inputMode="numeric"
                placeholder="75001"
                {...register('postalCode')}
                className={inputClass(theme)}
              />
            </Field>
            <Field label="Pays/Région" error={errors.country?.message} theme={theme}>
              <Controller
                name="country"
                control={control}
                render={({ field }) => (
                  <CountrySelect value={field.value} onChange={field.onChange} theme={theme} />
                )}
              />
            </Field>
          </div>
        </FormBlock>

        {/* === BLOCK 3 — Message + consent === */}
        <FormBlock
          ref={block3Ref}
          step={3}
          title="Votre message"
          subtitle="Dernière étape"
          active={revealed >= 3}
          theme={theme}
        >
          <Field
            label="Message"
            error={errors.message?.message}
            hint="Optionnel — quel est votre projet en quelques mots ?"
            theme={theme}
          >
            <textarea
              rows={4}
              placeholder="Contexte du bâtiment, contraintes particulières, urgence…"
              {...register('message')}
              className={`${inputClass(theme)} resize-none`}
            />
          </Field>

          <div className="mt-8 space-y-4">
            <label className="flex items-start gap-3 cursor-pointer group">
              <input
                type="checkbox"
                {...register('rgpd')}
                className={cn(
                  'mt-0.5 w-5 h-5 rounded border-2 text-primary focus:ring-2 focus:ring-primary/30 cursor-pointer',
                  dark ? 'border-white/30 bg-transparent' : 'border-foreground/20',
                )}
              />
              <span className={cn('text-sm font-body leading-relaxed', dark ? 'text-white/70' : 'text-foreground/70')}>
                J'accepte que Covalba traite mes données pour me recontacter.{' '}
                <a
                  href="/mentions-legales"
                  className={cn('underline underline-offset-2', dark ? 'hover:text-white' : 'hover:text-foreground')}
                  target="_blank"
                  rel="noreferrer"
                >
                  Politique de confidentialité
                </a>
                <span className={cn('ml-1', dark ? 'text-red-400' : 'text-[#d1290d]')}>*</span>
              </span>
            </label>
            {errors.rgpd && (
              <p role="alert" className={cn('text-xs font-body font-medium ml-8', dark ? 'text-red-400' : 'text-[#d1290d]')}>
                {errors.rgpd.message}
              </p>
            )}

            <label className="flex items-start gap-3 cursor-pointer group">
              <input
                type="checkbox"
                {...register('newsletter')}
                className={cn(
                  'mt-0.5 w-5 h-5 rounded border-2 text-primary focus:ring-2 focus:ring-primary/30 cursor-pointer',
                  dark ? 'border-white/30 bg-transparent' : 'border-foreground/20',
                )}
              />
              <span className={cn('text-sm font-body leading-relaxed', dark ? 'text-white/70' : 'text-foreground/70')}>
                Je souhaite recevoir occasionnellement les actualités Covalba (cas clients, conseils, nouveautés).
              </span>
            </label>
          </div>

          <div className="mt-10 space-y-3">
            <TurnstileCaptcha onToken={setCaptchaToken} theme={dark ? 'dark' : 'light'} />

            {errorSummary && (
              <p
                role="alert"
                className={cn(
                  'rounded-xl border px-4 py-3 font-body text-sm font-medium',
                  dark ? 'border-red-400/40 bg-red-400/10 text-red-300' : 'border-[#d1290d]/30 bg-[#d1290d]/5 text-[#d1290d]',
                )}
              >
                {errorSummary}
              </p>
            )}
            <button
              type="submit"
              disabled={isSubmitting}
              className="group w-full cta-gradient text-white font-semibold py-4 rounded-full transition-all duration-500 ease-[cubic-bezier(0.32,0.72,0,1)] hover:shadow-[0_8px_40px_rgba(153,20,55,0.35)] active:scale-[0.98] flex items-center justify-center gap-3 disabled:opacity-60 disabled:cursor-not-allowed"
            >
              <span>{isSubmitting ? 'Envoi en cours…' : 'Demander mon devis'}</span>
              {!isSubmitting && (
                <span className="flex items-center justify-center w-8 h-8 rounded-full bg-white/20 transition-transform duration-500 ease-[cubic-bezier(0.32,0.72,0,1)] group-hover:translate-x-0.5 group-hover:scale-105">
                  <ArrowRight className="w-4 h-4" />
                </span>
              )}
            </button>

            <p className={cn('text-xs text-center font-body', dark ? 'text-white/40' : 'text-foreground/40')}>Réponse sous 24h ouvrées</p>
          </div>
        </FormBlock>
      </form>
    </div>
  );
};
