'use client'
import React, { useState } from 'react'
import DjangoCSRFToken from '@/components/DjangoCSRFToken'
import Logo from '@/components/Logo';
import { useSearchParams, useRouter } from 'next/navigation'
import InputTextIcon from '@/components/InputTextIcon';
import Loader from '@/components/Loader'; // Importez le composant Loader
import Button from '@/components/Button'; // Importez le composant Button
import { User, KeySquare } from 'lucide-react'; // Importez directement les icônes nécessaires
import {
    FE_USERS_NEW_PASSWORD_URL,
    FE_ADMIN_SUBSCRIPTIONS_URL,
    FE_PARENTS_HOME_URL
} from '@/utils/Url';
import { login } from '@/app/actions/authAction';
import { getSession } from 'next-auth/react';
import { useCsrfToken } from '@/context/CsrfContext'; // Importez le hook useCsrfToken
import logger from '@/utils/logger';
import { useSession } from 'next-auth/react';
import ProfileSelector from '@/components/ProfileSelector'; // Importez le composant ProfileSelector

const useFakeData = process.env.NEXT_PUBLIC_USE_FAKE_DATA === 'true';

export default function Page() {
    const searchParams = useSearchParams();
    const [errorMessage, setErrorMessage] = useState("");
    const [userFieldError, setUserFieldError] = useState("")
    const [passwordFieldError, setPasswordFieldError] = useState("")
    const [selectedProfile, setSelectedProfile] = useState(1); // Par défaut, sélectionnez ADMIN

    const [isLoading, setIsLoading] = useState(false);

    const router = useRouter();
    const csrfToken = useCsrfToken(); // Utilisez le hook useCsrfToken

    function isOK(data) {
        return data.errorMessage === ""
    }

    function handleFormLogin(formData) {
        setIsLoading(true);

        login({
            email: formData.get('login'),
            password: formData.get('password'),
            role_type: selectedProfile // Utilisez le profil sélectionné
        }).then(result => {
            logger.debug('Sign In Result', result);
            setIsLoading(false);
            if (result.error) {
                setErrorMessage(result.error);
            } else {
                getSession().then(session => {
                    if (!session || !session.user) {
                        throw new Error('Session not found');
                    }
                    const user = session.user;
                    logger.debug('User Session:', user);

                    const roles = user.roles.filter(role => role.role_type === selectedProfile);
                    if (roles.length > 0) {
                        // const establishment = roles[0].establishment;
                        // localStorage.setItem('establishment_id', establishment);

                        // Redirection en fonction du rôle
                        if (roles[0].role_type === 1) {
                            router.push(FE_ADMIN_SUBSCRIPTIONS_URL);
                        } else if (roles[0].role_type === 2) {
                            router.push(FE_PARENTS_HOME_URL);
                        } else {
                            // Cas anormal
                        }
                    } else {
                        setErrorMessage('No roles found for the specified role type.');
                    }
                }).catch(error => {
                    logger.error('Error during session retrieval:', error);
                    setIsLoading(false);
                    setErrorMessage('An error occurred during session retrieval.');
                });
            }
        }).catch(error => {
            logger.error('Error during sign in:', error);
            setIsLoading(false);
            setErrorMessage('An error occurred during sign in.');
        });
    }

    if (isLoading === true) {
        return <Loader /> // Affichez le composant Loader
    } else {
        return <>
            <div className="container max mx-auto p-4">
                <div className="flex justify-center mb-4">
                    <Logo className="h-150 w-150" />
                </div>
                <h1 className="text-2xl font-bold text-center mb-4">Authentification</h1>
                <form className="max-w-md mx-auto" onSubmit={(e) => { e.preventDefault(); handleFormLogin(new FormData(e.target)); }}>
                    <DjangoCSRFToken csrfToken={csrfToken} />
                    <InputTextIcon name="login" type="text" IconItem={User} label="Identifiant" placeholder="Identifiant" errorMsg={userFieldError} className="w-full mb-5" />
                    <InputTextIcon name="password" type="password" IconItem={KeySquare} label="Mot de passe" placeholder="Mot de passe" errorMsg={passwordFieldError} className="w-full mb-5" />
                    <ProfileSelector selectedProfile={selectedProfile} setSelectedProfile={setSelectedProfile} />
                    <div className="input-group mb-4">
                    </div>
                    <label className="text-red-500">{errorMessage}</label>
                    <label><a className="float-right mb-4" href={`${FE_USERS_NEW_PASSWORD_URL}`}>Mot de passe oublié ?</a></label>
                    <div className="form-group-submit mt-4">
                        <Button text="Se Connecter" className="w-full" primary type="submit" name="connect" />
                    </div>
                </form>
            </div>
        </>
    }
};
