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

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);
        });
    }, [])


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

        if (res.success) {
            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>
}