import React, { useState, useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';
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';

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

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

  // Rediriger si déjà connecté
  if (isAuthenticated) {
    return <Navigate to="/dashboard" replace />;
  }

  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 (rememberMe) {
        localStorage.setItem('rememberedEmail', formData.email);
      } else {
        localStorage.removeItem('rememberedEmail');
      }
      await handleLogin(formData);
    }
  };

  const handleOAuthLogin = (provider: 'google' | 'github') => {
    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')} />
      </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}
          onChange={(e) => handleChange('email', e.target.value)}
          onBlur={() => handleBlur('email')}
          error={errors.email}
          required
          autoComplete="email"
        />
        <AuthInput
          type="password"
          label="Mot de passe"
          value={formData.password}
          onChange={(e) => handleChange('password', e.target.value)}
          onBlur={() => handleBlur('password')}
          error={errors.password}
          required
          autoComplete="current-password"
        />
        <div className="flex items-center">
          <input
            type="checkbox"
            id="rememberMe"
            checked={rememberMe}
            onChange={(e) => setRememberMe(e.target.checked)}
            className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            aria-describedby="rememberMe-description"
          />
          <label htmlFor="rememberMe" className="ml-2 block text-sm text-gray-900">
            Se souvenir de moi
          </label>
        </div>
        <p id="rememberMe-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;
