import styles from "./RegisterPage.module.css";
import Background from "../../components/Background/background.jsx";
import Input from "../../components/ui/input/input.tsx";
import Button from "../../components/ui/Button/button.tsx";
import {useContext, useEffect, useState} from "react";
import register from "../../utils/register.js";
import { useNavigate } from "react-router";
import { AuthContext } from "../../contexts/auth/AuthContext.js";
import Modal from "../../components/ui/modal/modal.tsx";


function RegisterPage() {

    const navigate = useNavigate();

    const [email, setEmail] = useState("");
    const [phone, setPhone] = useState("");
    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [name, setName] = useState("");
    const [lastName, setLastName] = useState("");
    const [open, setOpen] = useState(false);
    const [title, setTitle] = useState("");
    const [message, setMessage] = useState("");

    const { user, loading } = useContext(AuthContext)

    useEffect(() => {
        if (!loading && user) {
            navigate("/");
        }
    }, [loading, user]);

    const handleModal = (t, m) => {
        setTitle(t)
        setMessage(m)
        setOpen(true);
    }

    async function handleSubmit(e) {
        e.preventDefault();

        if(!(password === confirmPassword)) handleModal("Mot de passe invalide", "Les mots de passes ne conrrespondent pas");
        else if(password.length < 8) handleModal("Mot de passe invalide", "Le mot de passe doit faire plus de 8 charactères");
        else {

            const res = await register(email, password, name, lastName, phone);

            if (res.status === 422) {
                if (res.errors.email) handleModal("Adresse Email invalide", "Le formet de votre adresse Email n'est pas valide");
                if (res.errors.phone) handleModal("Numéro de téléphone invalide", "Le formet de votre numéro de téléphone n'est pas valide");
            } else navigate("/login");

        }
    }

    const handlePhone = (e) => {
        const value = e.target.value;
        if (value === "" || /^[0-9 +]+$/.test(value)) {
            setPhone(value);
        }
    };


    return <Background>

        <div className={styles.container}>

            <h1 className={styles.title}>Créer un compte</h1>

            <div className={`glassCard ${styles.inputContainer}`}>

                <div className={styles.formGroup}>
                    <Input
                        value={name}
                        placeholder="Prénom"
                        onChange={e => setName(e.target.value)}
                        style={{ width: '100%' }}
                    />
                </div>

                <div className={styles.formGroup}>
                    <Input
                        value={lastName}
                        placeholder="Nom"
                        onChange={e => setLastName(e.target.value)}
                        style={{ width: '100%' }}
                    />
                </div>

                <div className={styles.formGroup}>
                    <Input
                        type="email"
                        value={email}
                        placeholder="Adresse mail"
                        onChange={e => setEmail(e.target.value)}
                        style={{ width: '100%' }}
                    />
                </div>

                <div className={styles.formGroup}>
                    <Input
                        value={phone}
                        placeholder="Numéro de téléphone"
                        onChange={handlePhone}
                        style={{ width: '100%' }}
                    />
                </div>

                <div className={styles.formGroup}>
                    <Input password={true} onChange={e => setPassword(e.target.value)} value={password} placeholder={"Mot de passe"}/>
                </div>

                <div className={styles.formGroup}>
                    <Input password={true} onChange={e => setConfirmPassword(e.target.value)} value={confirmPassword} placeholder={"Confirmer le mot de passe"} />
                </div>

                <div className={styles.logButton}>
                    <Button variant={"transparent"} onClick={() => navigate("/login")}>Vous avez déjà un compte ?</Button>
                    <Button variant={"default"} onClick={handleSubmit}> Créer le compte </Button>
                </div>
            </div>
        </div>

        <Modal open={open} onClose={() => setOpen(false)} title={title}>
            <p>{message}</p>
        </Modal>

    </Background>
}

export default RegisterPage;


