'use client'

import React, { useState } from 'react';
import DjangoCSRFToken from '@/components/DjangoCSRFToken'
import Logo from '@/components/Logo';
import { useSearchParams } 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 Popup from '@/components/Popup'; // Importez le composant Popup
import { User } from 'lucide-react'; // Importez directement les icônes nécessaires
import { FE_USERS_LOGIN_URL } from '@/utils/Url';
import { useCsrfToken } from '@/context/CsrfContext';
import { sendNewPassword } from '@/app/actions/authAction';
import logger from '@/utils/logger';

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 [isLoading, setIsLoading] = useState(false);
    const [popupVisible, setPopupVisible] = useState(false);
    const [popupMessage, setPopupMessage] = useState("");
    const [popupConfirmAction, setPopupConfirmAction] = useState(null);
    const csrfToken = useCsrfToken();

    function validate(formData) {
        if (useFakeData) {
            setTimeout(() => {
                setUserFieldError("");
                setErrorMessage("");
                setPopupMessage("Mot de passe réinitialisé avec succès !");
                setPopupConfirmAction(() => () => setPopupVisible(false));
                setPopupVisible(true);
            }, 1000); // Simule un délai de traitement
        } else {
            const data = {email: formData.get('email')}
            sendNewPassword(data, csrfToken)
            .then(data => {
                logger.debug('Success:', data);
                setUserFieldError("");
                setErrorMessage("");
                if (data.errorMessage === "") {
                    setPopupMessage(data.message);
                    setPopupConfirmAction(() => () => setPopupVisible(false));
                    setPopupVisible(true);
                } else {
                    if (data.errorFields) {
                        setUserFieldError(data.errorFields.email);
                    }
                    if (data.errorMessage) {
                        setErrorMessage(data.errorMessage);
                    }
                }
            })
            .catch(error => {
                logger.error('Error fetching data:', error);
                error = error.errorMessage;
                logger.debug(error);
            });
        }
    }

    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">Nouveau Mot de passe</h1>
                <form className="max-w-md mx-auto" onSubmit={(e) => { e.preventDefault(); validate(new FormData(e.target)); }}>
                    <DjangoCSRFToken csrfToken={csrfToken} />
                    <InputTextIcon name="email" type="text" IconItem={User} label="Identifiant" placeholder="Identifiant" errorMsg={userFieldError} className="w-full" />
                    <p className="text-red-500">{errorMessage}</p>
                    <div className="form-group-submit mt-4">
                        <Button text="Réinitialiser" className="w-full" primary type="submit" name="validate" />
                    </div>
                </form>
                <br />
                <div className='flex justify-center mt-2 max-w-md mx-auto'>
                    <Button text="Annuler" className="w-full" href={ `${FE_USERS_LOGIN_URL}`} />
                </div>
            </div>
            <Popup
                visible={popupVisible}
                message={popupMessage}
                onConfirm={popupConfirmAction}
                onCancel={() => setPopupVisible(false)}
            />
        </>
    }
}