import { useNavigate, Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
import { LoginForm, LoginFormData } from '@/components/forms/LoginForm';
import { login } from '@/services/api/auth';
import { tokenManager } from '@/utils/token-manager';
import { useToast } from '@/hooks/useToast';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Alert, AlertDescription } from '@/components/ui/alert';

// T0166: Page de connexion qui utilise le composant LoginForm
// T0167: Intègre l'API de connexion avec support rememberMe
// T0170: Gestion d'erreurs améliorée avec messages spécifiques
export function Login() {
  const navigate = useNavigate();
  const { success, error: showErrorToast } = useToast();
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  // T0178: Vérifier s'il y a un message d'erreur stocké (session expirée)
  useEffect(() => {
    const authError = sessionStorage.getItem('auth_error');
    if (authError) {
      setError(authError);
      showErrorToast(authError);
      sessionStorage.removeItem('auth_error');
    }
  }, [showErrorToast]);

  /**
   * T0170: Convertit une erreur API en message d'erreur user-friendly
   */
  const getErrorMessage = (err: any): string => {
    // Erreur avec code (ApiError)
    if (err?.code) {
      switch (err.code) {
        case '401':
        case '403':
          return 'Invalid email or password. Please check your credentials and try again.';
        case '400':
          return err.message || 'Invalid request. Please check your input and try again.';
        case '429':
          return 'Too many login attempts. Please wait a moment and try again.';
        case '500':
        case '502':
        case '503':
          return 'Server error. Please try again later.';
        case 'NETWORK_ERROR':
          return 'Unable to connect to the server. Please check your internet connection and try again.';
        case 'UNKNOWN_ERROR':
          return err.message || 'An unexpected error occurred. Please try again.';
        default:
          return err.message || 'Login failed. Please try again.';
      }
    }

    // Erreur avec response (AxiosError)
    if (err?.response) {
      const status = err.response.status;
      if (status === 401 || status === 403) {
        return 'Invalid email or password. Please check your credentials and try again.';
      }
      if (status === 400) {
        return err.response.data?.error || err.response.data?.message || 'Invalid request. Please check your input and try again.';
      }
      if (status === 429) {
        return 'Too many login attempts. Please wait a moment and try again.';
      }
      if (status >= 500) {
        return 'Server error. Please try again later.';
      }
      return err.response.data?.error || err.response.data?.message || 'Login failed. Please try again.';
    }

    // Erreur réseau
    if (err?.request) {
      return 'Unable to connect to the server. Please check your internet connection and try again.';
    }

    // Message d'erreur par défaut
    return err?.message || 'Login failed. Please try again.';
  };

  const handleSubmit = async (data: LoginFormData) => {
    try {
      setError(null);
      setIsLoading(true);

      // T0167: Appel API avec rememberMe flag
      const response = await login({
        email: data.email,
        password: data.password,
        remember_me: data.rememberMe || false,
      });

      // Stocker les tokens avec tokenManager pour cohérence
      // T0167: Le backend gère déjà l'expiration (30 jours par défaut, 90 jours si rememberMe)
      tokenManager.setTokens(
        response.token.access_token,
        response.token.refresh_token,
        data.rememberMe || false
      );

      success('Login successful! Welcome back.');
      navigate('/dashboard');
    } catch (err: any) {
      // T0170: Gestion d'erreurs améliorée avec messages spécifiques
      const errorMessage = getErrorMessage(err);
      setError(errorMessage);
      showErrorToast(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="space-y-1">
          <CardTitle className="text-2xl text-center">Sign in</CardTitle>
          <CardDescription className="text-center">
            Enter your email and password to access your account
          </CardDescription>
        </CardHeader>
        <CardContent>
          {error && (
            <Alert variant="destructive" className="mb-4">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}
          <LoginForm onSubmit={handleSubmit} disabled={isLoading} />
          <div className="mt-4 text-center text-sm">
            Don't have an account?{' '}
            <Link to="/register" className="text-primary hover:underline">
              Sign up
            </Link>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

