"use client";

import { useRef, useState } from 'react';
import { useForm, Controller, type FieldErrors } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { ArrowRight, Check } from 'lucide-react';
import { toast } from 'sonner';
import { submitApplicateurToHubspot, type HubspotFormConfig } from '@/lib/hubspot';
import { pushFormSubmit } from '@/lib/dataLayer';
import { suggestEmail } from '@/lib/emailSuggest';
import { formatMissingFields, scrollToFirstError } from '@/lib/formErrors';
import {
  applicateurSchema,
  applicateurDefaultValues,
  type ApplicateurFormValues,
} from '@/lib/applicateurForm';
import { Field, textInputClass } from '@/components/diagnostic/Field';
import { PhoneField } from '@/components/diagnostic/PhoneField';
import { CountrySelect } from '@/components/diagnostic/CountrySelect';
import { CheckboxCards } from '@/components/diagnostic/CheckboxCards';
import { TurnstileCaptcha } from '@/components/forms/TurnstileCaptcha';

// clientele (multi) — the `value`s must stay IDENTICAL to the FR ones (sent to HubSpot),
// only the `label`s are translated to English.
const clienteleOptions = [
  { value: 'Particuliers', label: 'Individuals' },
  { value: 'Tertiaire', label: 'Tertiary' },
  { value: 'Industries', label: 'Industry' },
  { value: 'Grande distribution', label: 'Distribution' },
  { value: 'Collectivités', label: 'Community' },
] as const;

// Human-readable labels for the exhaustive error messages (translated).
const fieldLabels: Record<string, string> = {
  firstName: 'First name',
  lastName: 'Last name',
  email: 'Professional email',
  phone: 'Phone number',
  company: 'Company name',
  country: 'Country/Region',
  city: 'City',
  anneeCreation: 'Year company founded',
  chantierCoolRoof: 'Cool roof project already done',
  metier: 'Profession(s)',
  clientele: 'Market',
  source: 'Where did you hear about Covalba?',
  rgpd: 'Consent (checkbox)',
};

export const ApplicateurFormEN = ({ hubspotForm }: { hubspotForm?: HubspotFormConfig } = {}) => {
  const {
    control,
    register,
    handleSubmit,
    setValue,
    getValues,
    formState: { errors, isSubmitting },
  } = useForm<ApplicateurFormValues>({
    resolver: zodResolver(applicateurSchema),
    defaultValues: applicateurDefaultValues as ApplicateurFormValues,
    mode: 'onBlur',
  });

  const [submitted, setSubmitted] = useState(false);
  const [emailSuggestion, setEmailSuggestion] = useState<string | null>(null);
  const [errorSummary, setErrorSummary] = useState<string | null>(null);
  const [captchaToken, setCaptchaToken] = useState('');
  const formRef = useRef<HTMLFormElement>(null);
  const emailReg = register('email');

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

  const onSubmit = async (data: ApplicateurFormValues) => {
    if (!captchaToken) {
      toast.error('Please complete the captcha before submitting.');
      return;
    }
    try {
      await submitApplicateurToHubspot(data, hubspotForm, captchaToken);
    } catch (err) {
      console.error('[ApplicateurFormEN] HubSpot submit failed', err);
      toast.error('Submission failed. Please try again in a moment or contact us directly.');
      return;
    }
    // Submission confirmed on HubSpot: the GTM event is pushed only once.
    pushFormSubmit('form_applicateur_submit', 'applicateur');
    setSubmitted(true);
    toast.success('Application sent — the Covalba team will get back to you shortly.');
  };

  if (submitted) {
    return (
      <div className="rounded-lg border border-border bg-card p-5 shadow-sm lg:p-8">
        <div className="flex flex-col items-center py-8 text-center">
          <div className="mb-5 flex h-16 w-16 items-center justify-center rounded-full bg-green-100">
            <Check className="h-8 w-8 text-green-600" strokeWidth={2.5} />
          </div>
          <h3 className="font-satoshi text-2xl font-black tracking-tight text-foreground">Application sent!</h3>
          <p className="mt-3 max-w-md font-body leading-relaxed text-foreground/60">
            Thank you, your application has been successfully submitted. The Covalba team will get back to you to
            qualify the partnership and arrange the applicator training.
          </p>
        </div>
      </div>
    );
  }

  return (
    <form
      ref={formRef}
      onSubmit={handleSubmit(onSubmit, onInvalid)}
      className="space-y-5 rounded-lg border border-border bg-card p-5 shadow-sm lg:p-8"
      noValidate
    >
      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="First name" required error={errors.firstName?.message}>
          <input type="text" placeholder="John" {...register('firstName')} className={textInputClass} />
        </Field>
        <Field label="Last name" required error={errors.lastName?.message}>
          <input type="text" placeholder="Smith" {...register('lastName')} className={textInputClass} />
        </Field>
      </div>

      <Field label="Professional email" required error={errors.email?.message}>
        <input
          type="email"
          placeholder="john.smith@company.com"
          {...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={textInputClass}
        />
        {emailSuggestion && (
          <p className="mt-2 font-body text-xs text-foreground/70">
            Did you mean{' '}
            <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="Phone number" required error={errors.phone?.message}>
        <Controller
          name="phone"
          control={control}
          render={({ field }) => (
            <PhoneField value={field.value} onChange={field.onChange} onBlur={field.onBlur} />
          )}
        />
      </Field>

      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="Company name" error={errors.company?.message}>
          <input
            type="text"
            placeholder="Company name"
            {...register('company')}
            className={textInputClass}
          />
        </Field>
        <Field label="Country/Region" required error={errors.country?.message}>
          <Controller
            name="country"
            control={control}
            render={({ field }) => <CountrySelect value={field.value} onChange={field.onChange} />}
          />
        </Field>
      </div>

      <Field label="City" error={errors.city?.message}>
        <input type="text" placeholder="London" {...register('city')} className={textInputClass} />
      </Field>

      <Field
        label="Year company founded"
        required
        hint="Company must have been founded more than 2 years ago"
        error={errors.anneeCreation?.message}
      >
        <input
          type="number"
          inputMode="numeric"
          placeholder="2018"
          {...register('anneeCreation', { valueAsNumber: true })}
          className={textInputClass}
        />
      </Field>

      <label className="flex items-start gap-3 cursor-pointer">
        <input
          type="checkbox"
          {...register('chantierCoolRoof')}
          className="mt-0.5 h-5 w-5 cursor-pointer rounded border-2 border-foreground/20 text-primary focus:ring-2 focus:ring-primary/30"
        />
        <span className="font-body text-sm leading-relaxed text-foreground/70">
          I&apos;ve already done at least one cool roof project
        </span>
      </label>

      <Field label="Profession(s)" hint="Optional" error={errors.metier?.message}>
        <input
          type="text"
          placeholder="Waterproofing, insulation, industrial painting…"
          {...register('metier')}
          className={textInputClass}
        />
      </Field>

      <Controller
        name="clientele"
        control={control}
        render={({ field }) => (
          <Field
            label="Market"
            required
            hint="To join our network, more than 70% of your clients must be B2B"
            error={errors.clientele?.message as string | undefined}
          >
            <CheckboxCards
              options={clienteleOptions}
              value={field.value || []}
              onChange={field.onChange}
              columns="grid-cols-1 sm:grid-cols-2"
              ariaLabel="Market"
            />
          </Field>
        )}
      />

      <Field
        label="Where did you hear about Covalba?"
        required
        hint="Word of mouth, trade shows, LinkedIn, Facebook, Instagram, press…"
        error={errors.source?.message}
      >
        <input type="text" {...register('source')} className={textInputClass} />
      </Field>

      <label className="flex items-start gap-3 cursor-pointer">
        <input
          type="checkbox"
          {...register('rgpd')}
          className="mt-0.5 h-5 w-5 cursor-pointer rounded border-2 border-foreground/20 text-primary focus:ring-2 focus:ring-primary/30"
        />
        <span className="font-body text-sm leading-relaxed text-foreground/70">
          I agree that Covalba may process my data to get back to me.{' '}
          <a
            href="/mentions-legales"
            target="_blank"
            rel="noreferrer"
            className="underline underline-offset-2 hover:text-foreground"
          >
            Privacy policy
          </a>
          <span className="ml-1 text-[#d1290d]">*</span>
        </span>
      </label>
      {errors.rgpd && (
        <p role="alert" className="ml-8 font-body text-xs font-medium text-[#d1290d]">
          {errors.rgpd.message}
        </p>
      )}

      <TurnstileCaptcha onToken={setCaptchaToken} />

      {errorSummary && (
        <p
          role="alert"
          className="rounded-lg border border-[#d1290d]/30 bg-[#d1290d]/5 px-4 py-3 font-body text-sm font-medium text-[#d1290d]"
        >
          {errorSummary}
        </p>
      )}

      <button
        type="submit"
        disabled={isSubmitting}
        className="group flex w-full items-center justify-center gap-3 rounded-full cta-gradient py-4 font-semibold text-white 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] disabled:cursor-not-allowed disabled:opacity-60"
      >
        <span>{isSubmitting ? 'Sending…' : 'Submit my application'}</span>
        {!isSubmitting && (
          <span className="flex h-8 w-8 items-center justify-center 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="h-4 w-4" />
          </span>
        )}
      </button>

      <p className="text-xs leading-relaxed text-foreground/45">
        Your information is used by Covalba to process your applicator partnership request.
      </p>
    </form>
  );
};
