import styles from "../manageMember.module.css";
import Button from "../../../../../components/ui/button/button.tsx";
import modifyRole from "../../../../../utils/users/modifyRole.js";
import { useState, useEffect } from "react";
import getRoles from "../../../../../utils/getRoles.js";
import Modal from "../../../../../components/ui/modal/modal.tsx";

export default function ModifyRole({ user }) {

    const [roles, setRoles] = useState([]);
    const [selectedRole, setSelectedRole] = useState(3);
    const [open, setOpen] = useState(false);
    const [title, setTitle] = useState("");
    const [description, setDescription] = useState("");

    useEffect(() => {
        getRoles().then(data => {
            if (data) setRoles(data.data);
            //TODO: Fermer les modal + actualiser les infos lors du changement de role
        });
    }, [])


    const handleRoleUpdate = async () => {
        const res = await modifyRole(selectedRole, user.id);

        if (res.status === 200) {
            setDescription("Rôle modifié avec succès");
            setTitle("Modification")
            setOpen(true);
        } else {
            setDescription("Erreur lors de la modification du rôle");
            setTitle("Erreur")
            setOpen(true);
        }
    };


    return <div className={`${styles.manageBlockContent} ${styles.modifyRole}`}>
        <select
            value={selectedRole}
            onChange={(e) => setSelectedRole(e.target.value)}
            className={styles.select}
        >
            {roles.map((role, index) => (
                <option key={index} value={index+1}>
                    {role}
                </option>
            ))}
        </select>

        <Button onClick={handleRoleUpdate} variant={"default"}>
            Enregistrer
        </Button>

        <Modal open={open} onClose={() => setOpen(false)} title={title}>
            <p className={styles.modalContent}>{description}</p>
        </Modal>
    </div>
}