"use client";
import Checkbox from "@/components/form/input/Checkbox";
import Input from "@/components/form/input/InputField";
import Label from "@/components/form/Label";
import Button from "@/components/ui/button/Button";
import { loginUser } from "@/helpers/axios_helper";
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from "@/icons";
import Link from "next/link";
import React, { useState } from "react";
import { toast } from "react-toastify";
import { useRouter } from "next/navigation";
import {useAppDispatch} from "@/lib/hooks";
import {login, useUser} from "@/lib/features/user/userSlice";
import Cookies from "js-cookie";
import { signIn } from "next-auth/react";
import { useSession } from "next-auth/react";

interface ForgotPasswordData {
  firstName: string;
  lastName: string;
  email: string;
  clientCount: string;
  partnerCount: string;
}

export default function SignInForm() {
  const { data: session, status } = useSession();
  const router = useRouter();
  
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [authState, setAuthState] = useState<'login' | 'verifying' | 'success' | 'error' | 'forgot-password' | 'reset-password'>('login');
  const [userData, setUserData] = useState<any>(null);
  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  
  const dispatch = useAppDispatch()
  const user = useUser()
  
  const [errors, setErrors] = useState({
    email: "",
    password: "",
  });
  
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });

  const [forgotPasswordData, setForgotPasswordData] = useState<ForgotPasswordData>({
    firstName: '',
    lastName: '',
    email: '',
    clientCount: '',
    partnerCount: ''
  });

  const [resetPasswordData, setResetPasswordData] = useState({
    newPassword: '',
    confirmPassword: ''
  });

  // Keep this useEffect INSIDE the component
  React.useEffect(() => {
    if (status === "authenticated" && session) {
      if (session.user && session.user.id) {
        console.log("✅ Utilisateur déjà connecté, redirection vers / (accueil)");
        router.push("/");
      }
    }
  }, [status, session, router]);

  if (status === "authenticated" && session && session.user && session.user.id) {
    return null;
  }

  const validateForm = () => {
    let valid = true;
    const newErrors = {
      email: "",
      password: "",
    };

    if (!formData.email.trim()) {
      newErrors.email = "L'email est requis";
      valid = false;
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = "L'email est invalide";
      valid = false;
    }

    if (!formData.password) {
      newErrors.password = "Le mot de passe est requis";
      valid = false;
    } else if (formData.password.length < 4) {
      newErrors.password = "Le mot de passe doit contenir au moins 6 caractères";
      valid = false;
    }

    setErrors(newErrors);
    return valid;
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    if (errors[name as keyof typeof errors]) {
      setErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

  const handleForgotPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForgotPasswordData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleResetPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setResetPasswordData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;
    
    setLoading(true);
    setAuthState('verifying');
    
    try {
      const result = await signIn("credentials", {
        email: formData.email,
        password: formData.password,
        redirect: false,
      });
      
      if (result?.error) {
        setAuthState('error');
        setErrorMessage("Désolé, vos identifiants ne sont pas reconnus dans notre base de données. Veuillez vérifier votre email et mot de passe.");
      } else if (result?.ok) {
        // Toujours afficher le message de succès
        setAuthState('success');
        setSuccessMessage("Bienvenue ! Votre identité a été vérifiée avec succès.");
        
        // Redirection vers le dashboard principal
        setTimeout(() => {
          router.push("/");
        }, 500);
      }
    } catch (error) {
      setAuthState('error');
      setErrorMessage("Une erreur est survenue lors de la connexion. Veuillez réessayer.");
    } finally {
      setLoading(false);
    }
  };

  const handleForgotPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    
    try {
      const response = await fetch('/api/auth/verify-identity', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(forgotPasswordData)
      });
      
      const data = await response.json();
      
      if (response.ok) {
        setAuthState('reset-password');
        setUserData(data.user);
      } else {
        toast.error("Les informations fournies ne correspondent pas à notre base de données.");
      }
    } catch (error) {
      toast.error("Erreur lors de la vérification de l'identité.");
    } finally {
      setLoading(false);
    }
  };

  const handleResetPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (resetPasswordData.newPassword !== resetPasswordData.confirmPassword) {
      toast.error("Les mots de passe ne correspondent pas.");
      return;
    }
    
    if (resetPasswordData.newPassword.length < 6) {
      toast.error("Le mot de passe doit contenir au moins 6 caractères.");
      return;
    }
    
    setLoading(true);
    
    try {
      const response = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: forgotPasswordData.email,
          newPassword: resetPasswordData.newPassword
        })
      });
      
      if (response.ok) {
        toast.success("Mot de passe mis à jour avec succès ! Vous pouvez maintenant vous connecter.");
        setAuthState('login');
        setFormData({ email: forgotPasswordData.email, password: '' });
      } else {
        toast.error("Erreur lors de la mise à jour du mot de passe.");
      }
    } catch (error) {
      toast.error("Erreur lors de la mise à jour du mot de passe.");
    } finally {
      setLoading(false);
    }
  };

  const renderLoginForm = () => (
    <div className="flex flex-col flex-1 lg:w-1/2 w-full">
      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div>
          <div className="mb-8 text-center">
            <h1 className="mb-3 text-3xl font-bold text-gray-900 dark:text-white">
              Connexion
            </h1>
            <p className="text-gray-600 dark:text-gray-400">
              Accédez à votre espace de travail
            </p>
          </div>
          
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Email <span className="text-red-500">*</span>
              </Label>
              <Input
                name="email"
                placeholder="votre@email.com"
                type="email"
                value={formData.email}
                onChange={handleInputChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
              {errors.email && (
                <p className="mt-1 text-sm text-red-500">{errors.email}</p>
              )}
            </div>
            
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Mot de passe <span className="text-red-500">*</span>
              </Label>
              <div className="relative mt-1">
                <Input
                  name="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Votre mot de passe"
                  value={formData.password}
                  onChange={handleInputChange}
                  className="w-full px-4 py-3 pr-12 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
                >
                  {showPassword ? (
                    <EyeIcon className="w-5 h-5" />
                  ) : (
                    <EyeCloseIcon className="w-5 h-5" />
                  )}
                </button>
              </div>
              {errors.password && (
                <p className="mt-1 text-sm text-red-500">{errors.password}</p>
              )}
            </div>
            
            <div className="flex items-center justify-between">
              <button
                type="button"
                onClick={() => setAuthState('forgot-password')}
                className="text-sm text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
              >
                Mot de passe oublié ?
              </button>
            </div>
            
            <Button
              className="w-full py-3 text-white bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 rounded-lg font-medium transition-all duration-200 transform hover:scale-105"
              size="sm"
              type="submit"
              disabled={loading}
            >
              {loading ? (
                <>
                  <span className="inline-block h-4 w-4 animate-spin rounded-full border-2 border-solid border-white border-t-transparent mr-2" />
                  Connexion...
                </>
              ) : (
                "Se connecter"
              )}
            </Button>
          </form>
        </div>
      </div>
    </div>
  );

  const renderVerifyingState = () => (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800">
      <div className="text-center p-8 bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full mx-4">
        <div className="mb-6">
          <div className="w-16 h-16 mx-auto mb-4 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center">
            <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          </div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
            Vérification en cours
          </h2>
          <p className="text-gray-600 dark:text-gray-400">
            Veuillez patienter pendant que nous vérifions votre identité...
          </p>
        </div>
      </div>
    </div>
  );

  const renderSuccessState = () => (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-green-50 to-emerald-100 dark:from-gray-900 dark:to-gray-800">
      <div className="text-center p-8 bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full mx-4">
        <div className="mb-6">
          <div className="w-16 h-16 mx-auto mb-4 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
            <svg className="w-8 h-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
            Connexion réussie !
          </h2>
          <p className="text-gray-600 dark:text-gray-400">
            {successMessage}
          </p>
        </div>
      </div>
    </div>
  );

  const renderErrorState = () => (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-red-50 to-pink-100 dark:from-gray-900 dark:to-gray-800">
      <div className="text-center p-8 bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full mx-4">
        <div className="mb-6">
          <div className="w-16 h-16 mx-auto mb-4 bg-red-100 dark:bg-red-900 rounded-full flex items-center justify-center">
            <svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
            Échec de connexion
          </h2>
          <p className="text-gray-600 dark:text-gray-400 mb-6">
            {errorMessage}
          </p>
          <Button
            onClick={() => setAuthState('login')}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Réessayer
          </Button>
        </div>
      </div>
    </div>
  );

  const renderForgotPasswordForm = () => (
    <div className="flex flex-col flex-1 lg:w-1/2 w-full">
      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div>
          <div className="mb-8 text-center">
            <button
              onClick={() => setAuthState('login')}
              className="mb-4 flex items-center text-blue-600 hover:text-blue-800"
            >
              <ChevronLeftIcon className="w-4 h-4 mr-2" />
              Retour à la connexion
            </button>
            <h1 className="mb-3 text-3xl font-bold text-gray-900 dark:text-white">
              Mot de passe oublié
            </h1>
            <p className="text-gray-600 dark:text-gray-400">
              Répondez aux questions pour réinitialiser votre mot de passe
            </p>
          </div>
          
          <form onSubmit={handleForgotPassword} className="space-y-6">
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Prénom <span className="text-red-500">*</span>
              </Label>
              <Input
                name="firstName"
                placeholder="Votre prénom"
                value={forgotPasswordData.firstName}
                onChange={handleForgotPasswordChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
            </div>
            
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Nom <span className="text-red-500">*</span>
              </Label>
              <Input
                name="lastName"
                placeholder="Votre nom"
                value={forgotPasswordData.lastName}
                onChange={handleForgotPasswordChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
            </div>
            
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Email <span className="text-red-500">*</span>
              </Label>
              <Input
                name="email"
                type="email"
                placeholder="votre@email.com"
                value={forgotPasswordData.email}
                onChange={handleForgotPasswordChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
            </div>
            
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Nombre de clients créés <span className="text-red-500">*</span>
              </Label>
              <Input
                name="clientCount"
                type="number"
                placeholder="Nombre de clients"
                value={forgotPasswordData.clientCount}
                onChange={handleForgotPasswordChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
            </div>
            
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Nombre de partenaires créés <span className="text-red-500">*</span>
              </Label>
              <Input
                name="partnerCount"
                type="number"
                placeholder="Nombre de partenaires"
                value={forgotPasswordData.partnerCount}
                onChange={handleForgotPasswordChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
            </div>
            
            <Button
              className="w-full py-3 text-white bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 rounded-lg font-medium transition-all duration-200 transform hover:scale-105"
              size="sm"
              type="submit"
              disabled={loading}
            >
              {loading ? (
                <>
                  <span className="inline-block h-4 w-4 animate-spin rounded-full border-2 border-solid border-white border-t-transparent mr-2" />
                  Vérification...
                </>
              ) : (
                "Vérifier l'identité"
              )}
            </Button>
          </form>
        </div>
      </div>
    </div>
  );

  const renderResetPasswordForm = () => (
    <div className="flex flex-col flex-1 lg:w-1/2 w-full">
      <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
        <div>
          <div className="mb-8 text-center">
            <h1 className="mb-3 text-3xl font-bold text-gray-900 dark:text-white">
              Nouveau mot de passe
            </h1>
            <p className="text-gray-600 dark:text-gray-400">
              Créez votre nouveau mot de passe
            </p>
          </div>
          
          <form onSubmit={handleResetPassword} className="space-y-6">
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Nouveau mot de passe <span className="text-red-500">*</span>
              </Label>
              <Input
                name="newPassword"
                type="password"
                placeholder="Nouveau mot de passe"
                value={resetPasswordData.newPassword}
                onChange={handleResetPasswordChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
            </div>
            
            <div>
              <Label className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Confirmer le mot de passe <span className="text-red-500">*</span>
              </Label>
              <Input
                name="confirmPassword"
                type="password"
                placeholder="Confirmer le mot de passe"
                value={resetPasswordData.confirmPassword}
                onChange={handleResetPasswordChange}
                className="mt-1 w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
              />
            </div>
            
            <Button
              className="w-full py-3 text-white bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 rounded-lg font-medium transition-all duration-200 transform hover:scale-105"
              size="sm"
              type="submit"
              disabled={loading}
            >
              {loading ? (
                <>
                  <span className="inline-block h-4 w-4 animate-spin rounded-full border-2 border-solid border-white border-t-transparent mr-2" />
                  Mise à jour...
                </>
              ) : (
                "Mettre à jour le mot de passe"
              )}
            </Button>
          </form>
        </div>
      </div>
    </div>
  );

  switch (authState) {
    case 'verifying':
      return renderVerifyingState();
    case 'success':
      return renderSuccessState();
    case 'error':
      return renderErrorState();
    case 'forgot-password':
      return renderForgotPasswordForm();
    case 'reset-password':
      return renderResetPasswordForm();
    default:
      return renderLoginForm();
  }
}