'use client';

import { useState, Suspense } from 'react';
import { Link } from '@/i18n/navigation';
import Image from 'next/image';
import { useSearchParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useAuth } from '@/lib/context/auth-context';

interface FieldErrors {
  email?: string;
  password?: string;
}

type ErrorField = 'email' | 'password' | 'general';

function mapLoginError(
  error: any,
  t: (key: string) => string
): { message: string; field: ErrorField } {
  const errorMessage = error?.message || error?.response?.message || '';

  if (error?.name === 'TypeError' || errorMessage.includes('fetch')) {
    return { message: t('errors.network'), field: 'general' };
  }

  if (errorMessage.includes('Invalid credentials') || errorMessage.includes('Identifiants')) {
    return { message: t('errors.invalidCredentials'), field: 'general' };
  }

  if (errorMessage.includes('inactive') || errorMessage.includes('désactivé')) {
    return { message: t('errors.inactive'), field: 'general' };
  }

  if (errorMessage.includes('not found') || errorMessage.includes('introuvable')) {
    return { message: t('errors.notFound'), field: 'email' };
  }

  if (errorMessage.includes('password') || errorMessage.includes('mot de passe')) {
    return { message: t('errors.incorrectPassword'), field: 'password' };
  }

  if (errorMessage.includes('Too many') || errorMessage.includes('rate limit')) {
    return { message: t('errors.rateLimit'), field: 'general' };
  }

  return { message: errorMessage || t('errors.generic'), field: 'general' };
}

function LoginPageContent() {
  const { login } = useAuth();
  const searchParams = useSearchParams();
  const redirectTo = searchParams.get('redirect') || '/dashboard';
  const tLogin = useTranslations('auth.login');
  const tPanel = useTranslations('auth.sidePanel');
  const tFooter = useTranslations('auth.footerLinks');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});

  const validateForm = (): boolean => {
    const errors: FieldErrors = {};

    if (!email.trim()) {
      errors.email = tLogin('fieldErrors.emailRequired');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      errors.email = tLogin('fieldErrors.emailInvalid');
    }

    if (!password) {
      errors.password = tLogin('fieldErrors.passwordRequired');
    } else if (password.length < 6) {
      errors.password = tLogin('fieldErrors.passwordMin');
    }

    setFieldErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value);
  };

  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPassword(e.target.value);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setFieldErrors({});

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      await login(email, password, redirectTo, rememberMe);
    } catch (err: any) {
      const { message, field } = mapLoginError(err, tLogin);

      if (field === 'email') {
        setFieldErrors({ email: message });
      } else if (field === 'password') {
        setFieldErrors({ password: message });
      } else {
        setError(message);
      }
    } finally {
      setIsLoading(false);
    }
  };

  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-10">
            <Link href="/">
              <Image
                src="/assets/logos/logo-black.svg"
                alt="Xpeditis"
                width={50}
                height={60}
                priority
                className="h-auto"
              />
            </Link>
          </div>

          <div className="mb-8">
            <h1 className="text-h1 text-brand-navy mb-2">{tLogin('title')}</h1>
            <p className="text-body text-neutral-600">{tLogin('subtitle')}</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>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="email" className={`label ${fieldErrors.email ? 'text-red-600' : ''}`}>
                {tLogin('emailLabel')}
              </label>
              <input
                id="email"
                type="email"
                value={email}
                onChange={handleEmailChange}
                className={`input w-full ${
                  fieldErrors.email
                    ? 'border-red-500 focus:border-red-500 focus:ring-red-500 bg-red-50'
                    : ''
                }`}
                placeholder={tLogin('emailPlaceholder')}
                autoComplete="email"
                disabled={isLoading}
                aria-invalid={!!fieldErrors.email}
                aria-describedby={fieldErrors.email ? 'email-error' : undefined}
              />
              {fieldErrors.email && (
                <p
                  id="email-error"
                  className="mt-1.5 text-body-sm text-red-600 flex items-center gap-1"
                >
                  <svg className="w-4 h-4" 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>
                  {fieldErrors.email}
                </p>
              )}
            </div>

            <div>
              <label
                htmlFor="password"
                className={`label ${fieldErrors.password ? 'text-red-600' : ''}`}
              >
                {tLogin('passwordLabel')}
              </label>
              <input
                id="password"
                type="password"
                value={password}
                onChange={handlePasswordChange}
                className={`input w-full ${
                  fieldErrors.password
                    ? 'border-red-500 focus:border-red-500 focus:ring-red-500 bg-red-50'
                    : ''
                }`}
                placeholder={tLogin('passwordPlaceholder')}
                autoComplete="current-password"
                disabled={isLoading}
                aria-invalid={!!fieldErrors.password}
                aria-describedby={fieldErrors.password ? 'password-error' : undefined}
              />
              {fieldErrors.password && (
                <p
                  id="password-error"
                  className="mt-1.5 text-body-sm text-red-600 flex items-center gap-1"
                >
                  <svg className="w-4 h-4" 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>
                  {fieldErrors.password}
                </p>
              )}
            </div>

            <div className="flex items-center justify-between">
              <label className="flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={rememberMe}
                  onChange={e => setRememberMe(e.target.checked)}
                  className="w-4 h-4 text-accent border-neutral-300 rounded focus:ring-accent focus:ring-2"
                  disabled={isLoading}
                />
                <span className="ml-2 text-body-sm text-neutral-700">{tLogin('rememberMe')}</span>
              </label>

              <Link href="/forgot-password" className="text-body-sm link">
                {tLogin('forgotPassword')}
              </Link>
            </div>

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

          <div className="mt-8 text-center">
            <p className="text-body text-neutral-600">
              {tLogin('noAccount')}{' '}
              <Link href="/register" className="link font-semibold">
                {tLogin('createAccount')}
              </Link>
            </p>
          </div>

          <div className="mt-8 pt-8 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>

      <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">{tPanel('title')}</h2>
            <p className="text-body-lg text-neutral-200 mb-12">{tPanel('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="M13 10V3L4 14h7v7l9-11h-7z"
                    />
                  </svg>
                </div>
                <div className="ml-4">
                  <h3 className="text-h5 mb-1 text-white">
                    {tPanel('features.instantRates.title')}
                  </h3>
                  <p className="text-body-sm text-neutral-300">
                    {tPanel('features.instantRates.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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                </div>
                <div className="ml-4">
                  <h3 className="text-h5 mb-1 text-white">{tPanel('features.booking.title')}</h3>
                  <p className="text-body-sm text-neutral-300">
                    {tPanel('features.booking.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="M17 8h2a2 2 0 012 2v6a2 2 0 01-2 2h-2v4l-4-4H9a1.994 1.994 0 01-1.414-.586m0 0L11 14h4a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2v4l.586-.586z"
                    />
                  </svg>
                </div>
                <div className="ml-4">
                  <h3 className="text-h5 mb-1 text-white">{tPanel('features.tracking.title')}</h3>
                  <p className="text-body-sm text-neutral-300">
                    {tPanel('features.tracking.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">50+</div>
                <div className="text-body-sm text-neutral-300 mt-1">{tPanel('stats.carriers')}</div>
              </div>
              <div>
                <div className="text-display-sm text-brand-turquoise">10k+</div>
                <div className="text-body-sm text-neutral-300 mt-1">
                  {tPanel('stats.shipments')}
                </div>
              </div>
              <div>
                <div className="text-display-sm text-brand-turquoise">99.5%</div>
                <div className="text-body-sm text-neutral-300 mt-1">
                  {tPanel('stats.satisfaction')}
                </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>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense>
      <LoginPageContent />
    </Suspense>
  );
}
