import React, { useState, useEffect } from 'react';
import { Navigate, Link, useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { AuthLayout } from '../components/AuthLayout';
import { AuthInput } from '../components/AuthInput';
import { AuthButton } from '../components/AuthButton';
import { OAuthButton } from '../components/OAuthButton';
import { useLogin } from '../hooks/useLogin';
import type { LoginFormData } from '../types';
import { logger } from '@/utils/logger';

export function LoginPage() {
  const navigate = useNavigate();
  const { isAuthenticated, isLoading } = useAuthStore();
  const { mutate: handleLogin, isPending: loading, error } = useLogin();
  const [formData, setFormData] = useState<LoginFormData>({
    email: '',
    password: '',
  });
  const [errors, setErrors] = useState<
    Partial<Record<keyof LoginFormData, string>>
  >({});
  const [remember_me, setRemember_me] = useState(false);

  // Charger l'email sauvegardé au montage
  useEffect(() => {
    const savedEmail = localStorage.getItem('rememberedEmail');
    if (savedEmail) {
      setFormData((prev) => ({ ...prev, email: savedEmail }));
      setRemember_me(true);
    }
  }, []);

  // Rediriger si déjà connecté (mais attendre que le chargement soit terminé)
  // Ne pas rediriger pendant le login en cours
  // Vérifier aussi que le store est bien persisté
  if (isAuthenticated && !isLoading && !loading) {
    // Vérifier que le store est bien persisté avant de rediriger
    const stored = localStorage.getItem('auth-storage');
    if (stored) {
      try {
        const parsed = JSON.parse(stored);
        if (parsed.state?.user && parsed.state?.isAuthenticated) {
          return <Navigate to="/dashboard" replace />;
        }
      } catch (e) {
        // Continue, pas encore persisté
      }
    }
  }

  const validateField = (
    field: keyof LoginFormData,
    value: string,
  ): string | undefined => {
    switch (field) {
      case 'email':
        if (!value) return 'Email requis';
        if (!/\S+@\S+\.\S+/.test(value)) return 'Format email invalide';
        return undefined;
      case 'password':
        if (!value) return 'Mot de passe requis';
        if (value.length < 6)
          return 'Le mot de passe doit contenir au moins 6 caractères';
        return undefined;
      default:
        return undefined;
    }
  };

  const validate = (): boolean => {
    const newErrors: Partial<Record<keyof LoginFormData, string>> = {};
    const emailError = validateField('email', formData.email);
    const passwordError = validateField('password', formData.password);

    if (emailError) newErrors.email = emailError;
    if (passwordError) newErrors.password = passwordError;

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleBlur = (field: keyof LoginFormData) => {
    const error = validateField(field, formData[field]);
    setErrors({ ...errors, [field]: error });
  };

  const handleChange = (field: keyof LoginFormData, value: string) => {
    setFormData({ ...formData, [field]: value });
    // Clear error for this field when user starts typing
    if (errors[field]) {
      setErrors({ ...errors, [field]: undefined });
    }
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (validate()) {
      if (remember_me) {
        localStorage.setItem('rememberedEmail', formData.email);
      } else {
        localStorage.removeItem('rememberedEmail');
      }
      handleLogin(formData, {
        onSuccess: () => {
          // Redirection explicite après login réussi
          navigate('/dashboard', { replace: true });
        },
        onError: (err) => {
          // L'erreur est déjà gérée par le hook
          logger.error('Login error', {
            error: err instanceof Error ? err.message : String(err),
            stack: err instanceof Error ? err.stack : undefined,
          });
        },
      });
    }
  };

  const handleOAuthLogin = (provider: 'google' | 'github' | 'discord') => {
    window.location.href = `/api/v1/auth/oauth/${provider}`;
  };

  const formatErrorMessage = (error: Error | null): string => {
    if (!error) return '';

    const message = error.message.toLowerCase();
    const errorString = error.toString().toLowerCase();

    // Vérifier les codes d'erreur HTTP
    if (
      message.includes('invalid credentials') ||
      message.includes('401') ||
      errorString.includes('401')
    ) {
      return 'Email ou mot de passe incorrect';
    }
    if (
      message.includes('email not verified') ||
      message.includes('email_not_verified')
    ) {
      return "Votre email n'est pas vérifié. Vérifiez votre boîte mail.";
    }
    if (
      message.includes('network') ||
      message.includes('fetch') ||
      message.includes('network error')
    ) {
      return 'Erreur de connexion. Vérifiez votre connexion internet.';
    }
    if (
      message.includes('429') ||
      message.includes('rate limit') ||
      errorString.includes('429')
    ) {
      return 'Trop de tentatives. Veuillez réessayer dans quelques minutes.';
    }
    if (message.includes('500') || errorString.includes('500')) {
      return 'Erreur serveur. Veuillez réessayer plus tard.';
    }
    if (message.includes('403') || errorString.includes('403')) {
      return 'Accès refusé. Vérifiez vos permissions.';
    }

    return 'Une erreur est survenue. Veuillez réessayer.';
  };

  const hasEmailNotVerifiedError = (error: Error | null): boolean => {
    if (!error) return false;
    const message = error.message.toLowerCase();
    return (
      message.includes('email not verified') ||
      message.includes('email_not_verified')
    );
  };

  return (
    <AuthLayout
      title="Connexion"
      subtitle="Connectez-vous à votre compte"
      footerLinks={[
        { label: "Pas encore de compte ? S'inscrire", to: '/register' },
        { label: 'Mot de passe oublié ?', to: '/forgot-password' },
      ]}
    >
      <div
        className="space-y-2 mb-4"
        role="group"
        aria-label="Connexion avec un compte externe"
      >
        <OAuthButton
          provider="google"
          onClick={() => handleOAuthLogin('google')}
        />
        <OAuthButton
          provider="github"
          onClick={() => handleOAuthLogin('github')}
        />
        <OAuthButton
          provider="discord"
          onClick={() => handleOAuthLogin('discord')}
        />
      </div>
      <div className="relative my-4" role="separator" aria-label="Séparateur">
        <div className="absolute inset-0 flex items-center" aria-hidden="true">
          <div className="w-full border-t border-gray-300"></div>
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="px-2 bg-white text-gray-500" aria-hidden="true">
            Ou
          </span>
          <span className="sr-only">
            Ou connectez-vous avec email et mot de passe
          </span>
        </div>
      </div>
      <form
        onSubmit={onSubmit}
        className="space-y-4"
        aria-label="Formulaire de connexion"
      >
        {error && (
          <div
            className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded"
            role="alert"
            aria-live="assertive"
            aria-atomic="true"
          >
            <p className="font-medium">{formatErrorMessage(error)}</p>
            {hasEmailNotVerifiedError(error) && (
              <Link
                to="/verify-email"
                className="text-sm underline mt-1 block focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 rounded"
              >
                Renvoyer l'email de vérification
              </Link>
            )}
          </div>
        )}
        <AuthInput
          type="email"
          label="Email"
          value={formData.email}
          autoComplete="email"
          onChange={(e) => handleChange('email', e.target.value)}
          onBlur={() => handleBlur('email')}
          error={errors.email}
          required
        />
        <AuthInput
          type="password"
          label="Mot de passe"
          value={formData.password}
          autoComplete="current-password"
          onChange={(e) => handleChange('password', e.target.value)}
          onBlur={() => handleBlur('password')}
          error={errors.password}
          required
        />
        <div className="flex items-center">
          <input
            type="checkbox"
            id="remember_me"
            checked={remember_me}
            onChange={(e) => setRemember_me(e.target.checked)}
            className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            aria-describedby="remember_me-description"
          />
          <label
            htmlFor="remember_me"
            className="ml-2 block text-sm text-gray-900"
          >
            Se souvenir de moi
          </label>
        </div>
        <p id="remember_me-description" className="sr-only">
          Cocher cette case pour que votre email soit sauvegardé pour les
          prochaines connexions
        </p>
        <AuthButton type="submit" loading={loading}>
          Se connecter
        </AuthButton>
      </form>
    </AuthLayout>
  );
}

export default LoginPage;
