'use client'
// src/app/pages/subscribe.js

import React, { useState, useEffect } 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 Popup from '@/components/Popup';
import { FE_USERS_LOGIN_URL } from '@/utils/Url';
import { KeySquare } from 'lucide-react'; // Importez directement les icônes nécessaires
import { useCsrfToken } from '@/context/CsrfContext';
import { getResetPassword, resetPassword } 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 uuid = searchParams.get('uuid');
    const [errorMessage, setErrorMessage] = useState("");
    const [password1FieldError,setPassword1FieldError] = useState("")
    const [password2FieldError,setPassword2FieldError] = useState("")
    const [isLoading, setIsLoading] = useState(false);
    const [popupVisible, setPopupVisible] = useState(false);
    const [popupMessage, setPopupMessage] = useState("");

    const router = useRouter();
    const csrfToken = useCsrfToken();

    useEffect(() => {
        if (useFakeData) {
            setTimeout(() => {
                setIsLoading(false);
            }, 1000);
        } else {
            getResetPassword(uuid)
            .then(data => {
                logger.debug('Success:', data);
                setIsLoading(true);
                if(data.errorFields){
                    setPassword1FieldError(data.errorFields.password1)
                    setPassword2FieldError(data.errorFields.password2)
                }
                if(data.errorMessage){
                    setErrorMessage(data.errorMessage)
                }
                setIsLoading(false);
            })
            .catch(error => {
            logger.error('Error fetching data:', error);
            });
        }
      }, []);

    function validate(formData) {
        if (useFakeData) {
            setTimeout(() => {
                setPopupMessage("Mot de passe réinitialisé avec succès");
                setPopupVisible(true);
            }, 1000);
        } else {
            const data  = {
                password1: formData.get('password1'),
                password2: formData.get('password2'),
            }
            resetPassword(uuid,data,csrfToken)
            .then(data => {
                logger.debug('Success:', data);
                setPassword1FieldError("")
                setPassword2FieldError("")
                setErrorMessage("")
                if(data.errorMessage === ""){
                    setPopupMessage(data.message);
                    setPopupVisible(true);
                } else {
                    if(data.errorMessage){
                        setErrorMessage(data.errorMessage);
                    }
                    if(data.errorFields){
                        setPassword1FieldError(data.errorFields.password1)
                        setPassword2FieldError(data.errorFields.password2)
                    }
                }
            })
            .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 <>
            <Popup
                visible={popupVisible}
                message={popupMessage}
                onConfirm={() => {
                    setPopupVisible(false);
                    router.push(`${FE_USERS_LOGIN_URL}`);
                }}
                onCancel={() => setPopupVisible(false)}
            />
            <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">Réinitialisation du 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="password1" type="password" IconItem={KeySquare} label="Mot de passe" placeholder="Mot de passe" errorMsg={password1FieldError} className="w-full mb-5" />
                    <InputTextIcon name="password2" type="password" IconItem={KeySquare} label="Confirmation mot de passe" placeholder="Confirmation mot de passe" errorMsg={password2FieldError} className="w-full" />
                    <label className="text-red-500">{errorMessage}</label>
                    <div className="form-group-submit mt-4">
                        <Button text="Enregistrer" 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>
        </>
    }
}