'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'; // Importez le composant Popup
import { User, KeySquare } from 'lucide-react'; // Importez directement les icônes nécessaires
import { FE_USERS_LOGIN_URL  } from '@/utils/Url';
import { useCsrfToken } from '@/context/CsrfContext';
import { subscribe } from '@/app/actions/authAction';
const useFakeData = process.env.NEXT_PUBLIC_USE_FAKE_DATA === 'true';
import logger from '@/utils/logger';

export default function Page() {
    const searchParams = useSearchParams();

    const [errorMessage, setErrorMessage] = useState("");
    const [userFieldError,setUserFieldError] = 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) {
            setIsLoading(true);
            // Simuler une réponse réussie
            const data = {
                errorFields: {},
                errorMessage: ""
            };
            setUserFieldError("")
            setPassword1FieldError("")
            setPassword2FieldError("")
            setErrorMessage("")
            setIsLoading(false);
        }
      }, []);

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

    function subscribeFormSubmit(formData) {
        if (useFakeData) {
            // Simuler une réponse réussie
            const data = {
                errorFields: {},
                errorMessage: ""
            };
            setUserFieldError("")
            setPassword1FieldError("")
            setPassword2FieldError("")
            setErrorMessage("")
            if(isOK(data)){
                setPopupMessage("Votre compte a été créé avec succès");
                setPopupVisible(true);
            } else {
                if(data.errorMessage){
                    setErrorMessage(data.errorMessage);
                }
                if(data.errorFields){
                    setUserFieldError(data.errorFields.email)
                    setPassword1FieldError(data.errorFields.password1)
                    setPassword2FieldError(data.errorFields.password2)
                }
            }
        } else {
            const data ={
                email: formData.get('login'),
                password1: formData.get('password1'),
                password2: formData.get('password2'),
            }
            subscribe(data,csrfToken).then(data => {
                logger.debug('Success:', data);
                setUserFieldError("")
                setPassword1FieldError("")
                setPassword2FieldError("")
                setErrorMessage("")
                if(isOK(data)){
                    setPopupMessage(data.message);
                    setPopupVisible(true);
                } else {
                    if(data.errorMessage){
                        setErrorMessage(data.errorMessage);
                    }
                    if(data.errorFields){
                        setUserFieldError(data.errorFields.email)
                        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 <>
            <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 profil</h1>
                <form className="max-w-md mx-auto" onSubmit={(e) => { e.preventDefault();  subscribeFormSubmit(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="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" />
                    <p className="text-red-500">{errorMessage}</p>
                    <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" onClick={()=>{router.push(`${FE_USERS_LOGIN_URL}`)}} /></div>
            </div>
            <Popup
                visible={popupVisible}
                message={popupMessage}
                onConfirm={() => {
                    setPopupVisible(false);
                    router.push(`${FE_USERS_LOGIN_URL}`);
                }}
                onCancel={() => setPopupVisible(false)}
            />
        </>
    }
}