'use client';

import { useState, useEffect, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { Link, useRouter } from '@/i18n/navigation';
import Image from 'next/image';
import { useTranslations } from 'next-intl';
import { register } from '@/lib/api';
import { verifyInvitation, type InvitationResponse } from '@/lib/api/invitations';
import type { OrganizationType } from '@/types/api';

function RegisterPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useTranslations('auth.register');
  const tFooter = useTranslations('auth.footerLinks');

  const [step, setStep] = useState<1 | 2>(1);

  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  const [organizationName, setOrganizationName] = useState('');
  const [organizationType, setOrganizationType] = useState<OrganizationType>('FREIGHT_FORWARDER');
  const [siren, setSiren] = useState('');
  const [siret, setSiret] = useState('');
  const [street, setStreet] = useState('');
  const [city, setCity] = useState('');
  const [state, setState] = useState('');
  const [postalCode, setPostalCode] = useState('');
  const [country, setCountry] = useState('FR');

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const [invitationToken, setInvitationToken] = useState<string | null>(null);
  const [invitation, setInvitation] = useState<InvitationResponse | null>(null);
  const [isVerifyingInvitation, setIsVerifyingInvitation] = useState(false);

  useEffect(() => {
    const token = searchParams.get('token');
    if (token) {
      setIsVerifyingInvitation(true);
      verifyInvitation(token)
        .then(invitationData => {
          setInvitation(invitationData);
          setInvitationToken(token);
          setEmail(invitationData.email);
          setFirstName(invitationData.firstName);
          setLastName(invitationData.lastName);
        })
        .catch(() => {
          setError(t('invitationInvalid'));
        })
        .finally(() => {
          setIsVerifyingInvitation(false);
        });
    }
  }, [searchParams, t]);

  const validateStep1 = (): string | null => {
    if (!firstName.trim() || firstName.trim().length < 2) return t('fieldErrors.firstNameMin');
    if (!lastName.trim() || lastName.trim().length < 2) return t('fieldErrors.lastNameMin');
    if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
      return t('fieldErrors.emailInvalid');
    if (password.length < 12) return t('fieldErrors.passwordMin');
    if (password !== confirmPassword) return t('fieldErrors.passwordsMismatch');
    return null;
  };

  const handleStep1 = (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    const err = validateStep1();
    if (err) {
      setError(err);
      return;
    }
    if (invitationToken) {
      handleFinalSubmit();
    } else {
      setStep(2);
    }
  };

  const validateStep2 = (): string | null => {
    if (!organizationName.trim()) return t('fieldErrors.orgNameRequired');
    if (!/^[0-9]{9}$/.test(siren)) return t('fieldErrors.sirenRequired');
    if (siret && !/^[0-9]{14}$/.test(siret)) return t('fieldErrors.siretInvalid');
    if (!street.trim() || !city.trim() || !postalCode.trim() || !country.trim()) {
      return t('fieldErrors.addressRequired');
    }
    return null;
  };

  const handleStep2 = (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    const err = validateStep2();
    if (err) {
      setError(err);
      return;
    }
    handleFinalSubmit();
  };

  const handleFinalSubmit = async () => {
    setIsLoading(true);
    setError('');

    try {
      await register({
        email,
        password,
        firstName,
        lastName,
        ...(invitationToken
          ? { invitationToken }
          : {
              organization: {
                name: organizationName,
                type: organizationType,
                siren,
                siret: siret || undefined,
                street,
                city,
                state: state || undefined,
                postalCode,
                country: country.toUpperCase(),
              },
            }),
      });
      router.push('/dashboard');
    } catch (err: any) {
      setError(err.message || t('errors.generic'));
    } finally {
      setIsLoading(false);
    }
  };

  const rightPanel = (
    <div className="hidden lg:block lg:w-1/2 relative bg-brand-navy">
      <div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-800 opacity-95"></div>
      <div className="absolute inset-0 flex flex-col justify-center px-16 xl:px-24 text-white">
        <div className="max-w-xl">
          <h2 className="text-display-sm mb-6 text-white">
            {invitation ? t('sidePanel.titleInvitation') : t('sidePanel.titleDefault')}
          </h2>
          <p className="text-body-lg text-neutral-200 mb-12">{t('sidePanel.description')}</p>
          <div className="space-y-6">
            <div className="flex items-start">
              <div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
                <svg
                  className="w-6 h-6 text-white"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M5 13l4 4L19 7"
                  />
                </svg>
              </div>
              <div className="ml-4">
                <h3 className="text-h5 mb-1 text-white">{t('sidePanel.features.trial.title')}</h3>
                <p className="text-body-sm text-neutral-300">
                  {t('sidePanel.features.trial.description')}
                </p>
              </div>
            </div>
            <div className="flex items-start">
              <div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
                <svg
                  className="w-6 h-6 text-white"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                  />
                </svg>
              </div>
              <div className="ml-4">
                <h3 className="text-h5 mb-1 text-white">
                  {t('sidePanel.features.security.title')}
                </h3>
                <p className="text-body-sm text-neutral-300">
                  {t('sidePanel.features.security.description')}
                </p>
              </div>
            </div>
            <div className="flex items-start">
              <div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
                <svg
                  className="w-6 h-6 text-white"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z"
                  />
                </svg>
              </div>
              <div className="ml-4">
                <h3 className="text-h5 mb-1 text-white">{t('sidePanel.features.support.title')}</h3>
                <p className="text-body-sm text-neutral-300">
                  {t('sidePanel.features.support.description')}
                </p>
              </div>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-8 mt-12 pt-12 border-t border-neutral-700">
            <div>
              <div className="text-display-sm text-brand-turquoise">2k+</div>
              <div className="text-body-sm text-neutral-300 mt-1">
                {t('sidePanel.stats.companies')}
              </div>
            </div>
            <div>
              <div className="text-display-sm text-brand-turquoise">150+</div>
              <div className="text-body-sm text-neutral-300 mt-1">
                {t('sidePanel.stats.countries')}
              </div>
            </div>
            <div>
              <div className="text-display-sm text-brand-turquoise">24/7</div>
              <div className="text-body-sm text-neutral-300 mt-1">
                {t('sidePanel.stats.support')}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="absolute bottom-0 right-0 opacity-10">
        <svg width="400" height="400" viewBox="0 0 400 400" fill="none">
          <circle
            cx="200"
            cy="200"
            r="150"
            stroke="currentColor"
            strokeWidth="2"
            className="text-white"
          />
          <circle
            cx="200"
            cy="200"
            r="100"
            stroke="currentColor"
            strokeWidth="2"
            className="text-white"
          />
          <circle
            cx="200"
            cy="200"
            r="50"
            stroke="currentColor"
            strokeWidth="2"
            className="text-white"
          />
        </svg>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen flex">
      <div className="w-full lg:w-1/2 flex flex-col justify-center px-8 sm:px-12 lg:px-16 xl:px-24 bg-white">
        <div className="max-w-md w-full mx-auto">
          <div className="mb-8">
            <Link href="/">
              <Image
                src="/assets/logos/logo-black.svg"
                alt="Xpeditis"
                width={50}
                height={60}
                priority
                className="h-auto"
              />
            </Link>
          </div>

          {!invitation && (
            <div className="mb-8">
              <div className="flex items-center gap-3">
                <div className="flex items-center gap-2">
                  <div
                    className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-colors ${
                      step >= 1 ? 'bg-brand-navy text-white' : 'bg-neutral-100 text-neutral-400'
                    }`}
                  >
                    {step > 1 ? (
                      <svg
                        className="w-4 h-4"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2.5}
                          d="M5 13l4 4L19 7"
                        />
                      </svg>
                    ) : (
                      '1'
                    )}
                  </div>
                  <span
                    className={`text-body-sm font-medium ${step >= 1 ? 'text-brand-navy' : 'text-neutral-400'}`}
                  >
                    {t('stepAccount')}
                  </span>
                </div>
                <div
                  className={`flex-1 h-0.5 transition-colors ${step >= 2 ? 'bg-brand-navy' : 'bg-neutral-200'}`}
                />
                <div className="flex items-center gap-2">
                  <div
                    className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold transition-colors ${
                      step >= 2 ? 'bg-brand-navy text-white' : 'bg-neutral-100 text-neutral-400'
                    }`}
                  >
                    2
                  </div>
                  <span
                    className={`text-body-sm font-medium ${step >= 2 ? 'text-brand-navy' : 'text-neutral-400'}`}
                  >
                    {t('stepOrganization')}
                  </span>
                </div>
              </div>
            </div>
          )}

          <div className="mb-6">
            {isVerifyingInvitation ? (
              <p className="text-body text-neutral-600">{t('invitationVerifying')}</p>
            ) : invitation ? (
              <>
                <h1 className="text-h1 text-brand-navy mb-2">{t('invitationTitle')}</h1>
                <div className="p-3 bg-green-50 border border-green-200 rounded-lg">
                  <p className="text-body-sm text-green-800">{t('invitationValid')}</p>
                </div>
              </>
            ) : step === 1 ? (
              <>
                <h1 className="text-h1 text-brand-navy mb-2">{t('title')}</h1>
                <p className="text-body text-neutral-600">{t('subtitle')}</p>
              </>
            ) : (
              <>
                <h1 className="text-h1 text-brand-navy mb-2">{t('orgStepTitle')}</h1>
                <p className="text-body text-neutral-600">{t('orgStepSubtitle')}</p>
              </>
            )}
          </div>

          {error && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
              <svg
                className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
              <p className="text-body-sm text-red-800">{error}</p>
            </div>
          )}

          {(step === 1 || invitation) && !isVerifyingInvitation && (
            <form onSubmit={handleStep1} className="space-y-5">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="firstName" className="label">
                    {t('firstNameLabel')}
                  </label>
                  <input
                    id="firstName"
                    type="text"
                    required
                    value={firstName}
                    onChange={e => setFirstName(e.target.value)}
                    className="input w-full"
                    placeholder={t('firstNamePlaceholder')}
                    disabled={isLoading || !!invitation}
                  />
                </div>
                <div>
                  <label htmlFor="lastName" className="label">
                    {t('lastNameLabel')}
                  </label>
                  <input
                    id="lastName"
                    type="text"
                    required
                    value={lastName}
                    onChange={e => setLastName(e.target.value)}
                    className="input w-full"
                    placeholder={t('lastNamePlaceholder')}
                    disabled={isLoading || !!invitation}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="email" className="label">
                  {t('emailLabel')}
                </label>
                <input
                  id="email"
                  type="email"
                  required
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  className="input w-full"
                  placeholder={t('emailPlaceholder')}
                  autoComplete="email"
                  disabled={isLoading || !!invitation}
                />
              </div>

              <div>
                <label htmlFor="password" className="label">
                  {t('passwordLabel')}
                </label>
                <input
                  id="password"
                  type="password"
                  required
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                  className="input w-full"
                  placeholder={t('passwordPlaceholder')}
                  autoComplete="new-password"
                  disabled={isLoading}
                />
                <p className="mt-1.5 text-body-xs text-neutral-500">{t('passwordHint')}</p>
              </div>

              <div>
                <label htmlFor="confirmPassword" className="label">
                  {t('confirmPasswordLabel')}
                </label>
                <input
                  id="confirmPassword"
                  type="password"
                  required
                  value={confirmPassword}
                  onChange={e => setConfirmPassword(e.target.value)}
                  className="input w-full"
                  placeholder={t('passwordPlaceholder')}
                  autoComplete="new-password"
                  disabled={isLoading}
                />
              </div>

              <button
                type="submit"
                disabled={isLoading}
                className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed mt-2"
              >
                {isLoading ? t('submitting') : invitation ? t('submit') : t('continue')}
              </button>

              <p className="text-body-xs text-center text-neutral-500">
                {t('termsAccept')}{' '}
                <Link href="/terms" className="link">
                  {t('termsLink')}
                </Link>{' '}
                {t('termsAnd')}{' '}
                <Link href="/privacy" className="link">
                  {t('privacyLink')}
                </Link>
              </p>
            </form>
          )}

          {step === 2 && !invitation && (
            <form onSubmit={handleStep2} className="space-y-5">
              <div>
                <label htmlFor="organizationName" className="label">
                  {t('organizationNameLabel')} *
                </label>
                <input
                  id="organizationName"
                  type="text"
                  required
                  value={organizationName}
                  onChange={e => setOrganizationName(e.target.value)}
                  className="input w-full"
                  placeholder={t('organizationNamePlaceholder')}
                  disabled={isLoading}
                />
              </div>

              <div>
                <label htmlFor="organizationType" className="label">
                  {t('organizationTypeLabel')} *
                </label>
                <select
                  id="organizationType"
                  value={organizationType}
                  onChange={e => setOrganizationType(e.target.value as OrganizationType)}
                  className="input w-full"
                  disabled={isLoading}
                >
                  <option value="FREIGHT_FORWARDER">{t('orgTypes.freightForwarder')}</option>
                  <option value="SHIPPER">{t('orgTypes.shipper')}</option>
                  <option value="CARRIER">{t('orgTypes.carrier')}</option>
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="siren" className="label">
                    {t('sirenLabel')} *
                  </label>
                  <input
                    id="siren"
                    type="text"
                    required
                    value={siren}
                    onChange={e => setSiren(e.target.value.replace(/\D/g, '').slice(0, 9))}
                    className="input w-full"
                    placeholder="123456789"
                    maxLength={9}
                    disabled={isLoading}
                  />
                  <p className="mt-1 text-body-xs text-neutral-500">{t('sirenHint')}</p>
                </div>
                <div>
                  <label htmlFor="siret" className="label">
                    {t('siretLabel')}{' '}
                    <span className="text-neutral-400 font-normal">{t('siretOptional')}</span>
                  </label>
                  <input
                    id="siret"
                    type="text"
                    value={siret}
                    onChange={e => setSiret(e.target.value.replace(/\D/g, '').slice(0, 14))}
                    className="input w-full"
                    placeholder="12345678900014"
                    maxLength={14}
                    disabled={isLoading}
                  />
                  <p className="mt-1 text-body-xs text-neutral-500">{t('siretHint')}</p>
                </div>
              </div>

              <div>
                <label htmlFor="street" className="label">
                  {t('streetLabel')} *
                </label>
                <input
                  id="street"
                  type="text"
                  required
                  value={street}
                  onChange={e => setStreet(e.target.value)}
                  className="input w-full"
                  placeholder={t('streetPlaceholder')}
                  disabled={isLoading}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="city" className="label">
                    {t('cityLabel')} *
                  </label>
                  <input
                    id="city"
                    type="text"
                    required
                    value={city}
                    onChange={e => setCity(e.target.value)}
                    className="input w-full"
                    placeholder={t('cityPlaceholder')}
                    disabled={isLoading}
                  />
                </div>
                <div>
                  <label htmlFor="postalCode" className="label">
                    {t('postalCodeLabel')} *
                  </label>
                  <input
                    id="postalCode"
                    type="text"
                    required
                    value={postalCode}
                    onChange={e => setPostalCode(e.target.value)}
                    className="input w-full"
                    placeholder={t('postalCodePlaceholder')}
                    disabled={isLoading}
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="state" className="label">
                    {t('stateLabel')}{' '}
                    <span className="text-neutral-400 font-normal">{t('stateOptional')}</span>
                  </label>
                  <input
                    id="state"
                    type="text"
                    value={state}
                    onChange={e => setState(e.target.value)}
                    className="input w-full"
                    placeholder={t('statePlaceholder')}
                    disabled={isLoading}
                  />
                </div>
                <div>
                  <label htmlFor="country" className="label">
                    {t('countryLabel')} *
                  </label>
                  <input
                    id="country"
                    type="text"
                    required
                    value={country}
                    onChange={e => setCountry(e.target.value.toUpperCase().slice(0, 2))}
                    className="input w-full"
                    placeholder={t('countryPlaceholder')}
                    maxLength={2}
                    disabled={isLoading}
                  />
                  <p className="mt-1 text-body-xs text-neutral-500">{t('countryHint')}</p>
                </div>
              </div>

              <div className="flex gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => {
                    setStep(1);
                    setError('');
                  }}
                  disabled={isLoading}
                  className="btn-secondary flex-1 text-lg disabled:opacity-50"
                >
                  {t('back')}
                </button>
                <button
                  type="submit"
                  disabled={isLoading}
                  className="btn-primary flex-2 flex-1 text-lg disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoading ? t('submitting') : t('submit')}
                </button>
              </div>

              <p className="text-body-xs text-center text-neutral-500">
                {t('termsAccept')}{' '}
                <Link href="/terms" className="link">
                  {t('termsLink')}
                </Link>{' '}
                {t('termsAnd')}{' '}
                <Link href="/privacy" className="link">
                  {t('privacyLink')}
                </Link>
              </p>
            </form>
          )}

          <div className="mt-8 text-center">
            <p className="text-body text-neutral-600">
              {t('hasAccount')}{' '}
              <Link href="/login" className="link font-semibold">
                {t('login')}
              </Link>
            </p>
          </div>

          <div className="mt-6 pt-6 border-t border-neutral-200">
            <div className="flex flex-wrap justify-center gap-6 text-body-sm text-neutral-500">
              <Link href="/contact" className="hover:text-accent transition-colors">
                {tFooter('contact')}
              </Link>
              <Link href="/privacy" className="hover:text-accent transition-colors">
                {tFooter('privacy')}
              </Link>
              <Link href="/terms" className="hover:text-accent transition-colors">
                {tFooter('terms')}
              </Link>
            </div>
          </div>
        </div>
      </div>

      {rightPanel}
    </div>
  );
}

export default function RegisterPage() {
  return (
    <Suspense>
      <RegisterPageContent />
    </Suspense>
  );
}
