"use client";

import { useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Loader2, Mail, Lock, Shield } from "lucide-react";

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const router = useRouter();

  // Fonction pour traduire les erreurs Supabase en français
  const getErrorMessage = (error: string) => {
    const errorMessages: { [key: string]: string } = {
      "Invalid login credentials": "Identifiants de connexion invalides",
      "Email not confirmed": "Email non confirmé",
      "Too many requests": "Trop de tentatives de connexion",
      "User not found": "Utilisateur non trouvé",
      "Invalid email": "Adresse email invalide",
      "Password should be at least 6 characters": "Le mot de passe doit contenir au moins 6 caractères",
      "Email rate limit exceeded": "Limite de tentatives dépassée",
      "Invalid email or password": "Email ou mot de passe incorrect",
      "Account not found": "Compte non trouvé",
      "Invalid credentials": "Identifiants incorrects",
      "Authentication failed": "Échec de l'authentification",
      "Access denied": "Accès refusé",
      "Unauthorized": "Non autorisé",
    };

    // Chercher une correspondance exacte
    if (errorMessages[error]) {
      return errorMessages[error];
    }

    // Chercher une correspondance partielle
    for (const [englishError, frenchError] of Object.entries(errorMessages)) {
      if (error.toLowerCase().includes(englishError.toLowerCase())) {
        return frenchError;
      }
    }

    // Message par défaut si aucune correspondance
    return "Erreur de connexion. Vérifiez vos identifiants.";
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError("");

    // Validation côté client
    if (!email || !password) {
      setError("Veuillez remplir tous les champs");
      setLoading(false);
      return;
    }

    if (!email.includes("@")) {
      setError("Veuillez entrer une adresse email valide");
      setLoading(false);
      return;
    }

    const supabase = createClient();

    try {
      const { data, error: authError } = await supabase.auth.signInWithPassword({
        email,
        password,
      });

      if (authError) {
        setError(getErrorMessage(authError.message));
        return;
      }

      if (data.user) {
        router.push("/");
        router.refresh();
      }
    } catch (error) {
      console.error('Login error:', error);
      setError("Une erreur inattendue est survenue. Veuillez réessayer.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
      <Card className="w-full max-w-md shadow-lg border border-gray-200">
        <CardHeader className="space-y-6 pb-8">
          <div className="flex justify-center">
            <div className="relative w-16 h-16 rounded-full bg-gray-100 p-2">
              <Image
                src="/img/logo.png"
                alt="Logo"
                width={48}
                height={48}
                className="rounded-full"
              />
            </div>
          </div>
          <div className="text-center space-y-2">
            <CardTitle className="text-2xl font-bold text-gray-900 flex items-center justify-center gap-2">
              <Shield className="w-6 h-6 text-gray-700" />
              Admin Dashboard
            </CardTitle>
            <p className="text-gray-600 text-sm">
              Connectez-vous pour accéder au tableau de bord
            </p>
          </div>
        </CardHeader>
        
        <CardContent className="space-y-6">
          {error && (
            <Alert className="border-red-200 bg-red-50">
              <AlertDescription className="text-red-700">
                {error}
              </AlertDescription>
            </Alert>
          )}
          
          <form onSubmit={handleLogin} className="space-y-4">
            <div className="space-y-2">
              <label htmlFor="email" className="text-sm font-medium text-gray-700">
                Email
              </label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  id="email"
                  type="email"
                  placeholder="admin@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="pl-10 border-gray-300 focus:border-gray-900 focus:ring-gray-900"
                  required
                />
              </div>
            </div>
            
            <div className="space-y-2">
              <label htmlFor="password" className="text-sm font-medium text-gray-700">
                Mot de passe
              </label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  id="password"
                  type="password"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="pl-10 border-gray-300 focus:border-gray-900 focus:ring-gray-900"
                  required
                />
              </div>
            </div>
            
            <Button
              type="submit"
              className="w-full bg-gray-900 hover:bg-gray-800 text-white font-medium py-2.5 transition-colors"
              disabled={loading}
            >
              {loading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Connexion en cours...
                </>
              ) : (
                "Se connecter"
              )}
            </Button>
          </form>
          
          <div className="text-center">
            <p className="text-xs text-gray-500">
              Accès réservé aux administrateurs autorisés
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
