import React, { useState, useEffect } from 'react';
import { Navigate, Link, useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
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';
import { CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { AlertCircle } from 'lucide-react';
import { AuthLayout } from '../components/AuthLayout';

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é)
  if (isAuthenticated && !isLoading && !loading) {
    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 });
    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: () => {
          navigate('/dashboard', { replace: true });
        },
        onError: (err) => {
          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();

    if (message.includes('invalid credentials') || message.includes('401') || errorString.includes('401')) {
      return 'Incorrect email or password';
    }
    if (message.includes('email not verified')) {
      return "Your email is not verified. Check your inbox.";
    }
    if (message.includes('network')) {
      return 'Connection error. Check your internet.';
    }
    return 'An error occurred. Please try again.';
  };

  return (
    <AuthLayout
      title="Welcome Back"
      subtitle="Sign in to your account"
      footerLinks={[{ label: "Don't have an account? Sign up", to: '/register' }]}
    >
      <div className="space-y-6">
        <div className="flex flex-col gap-3">
          <OAuthButton provider="google" onClick={() => handleOAuthLogin('google')} />
          <OAuthButton provider="github" onClick={() => handleOAuthLogin('github')} />
          <OAuthButton provider="discord" onClick={() => handleOAuthLogin('discord')} />
        </div>

        <div className="relative flex justify-center text-xs uppercase">
          <div className="absolute inset-0 flex items-center"><span className="w-full border-t border-white/10" /></div>
          <span className="bg-background px-2 text-muted-foreground relative z-10">Or continue with</span>
        </div>

        <form onSubmit={onSubmit} className="space-y-4">
          {error && (
            <div className="bg-destructive/10 border border-destructive/30 text-destructive px-4 py-3 rounded-lg text-sm flex items-center gap-2">
              <AlertCircle className="w-4 h-4 flex-shrink-0" />
              <p>{formatErrorMessage(error)}</p>
            </div>
          )}

          <div className="space-y-4">
            <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="Password"
              value={formData.password}
              autoComplete="current-password"
              onChange={(e) => handleChange('password', e.target.value)}
              onBlur={() => handleBlur('password')}
              error={errors.password}
              required
            />
          </div>

          <div className="flex items-center justify-between text-sm">
            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                id="remember_me"
                checked={remember_me}
                onChange={(e) => setRemember_me(e.target.checked)}
                className="h-4 w-4 rounded border-white/10 bg-black/20 text-primary focus:ring-primary/50"
              />
              <label htmlFor="remember_me" className="text-muted-foreground">Remember me</label>
            </div>
            <Link to="/forgot-password" className="text-primary hover:underline">Forgot password?</Link>
          </div>

          <AuthButton type="submit" loading={loading} className="w-full bg-gradient-to-r from-cyan-600 to-magenta-600 hover:from-cyan-500 hover:to-magenta-500 text-white border-0 shadow-lg shadow-cyan-900/20">
            Sign In
          </AuthButton>
        </form>
      </div>
    </AuthLayout>
  );
}

export default LoginPage;
