import {ReactNode, useContext, useEffect, useState} from "react";
import Button from "../../../../components/ui/Button/Button";
import Modal from "../../../../components/ui/Modal/Modal";
import User from "../../../Volunteers/interfaces/user.interface";
import getAllUser from "../../../../utils/users/getAllUsers";
import Loading from "../../../../components/ui/Loading/Loading";
import getUserById from "../../../../utils/users/getUserById";
import styles from "./AssignUserBtn.module.css";
import {AuthContext} from "../../../../contexts/Auth/AuthContext";
import assignOtherUser from "../../../../utils/tasks/assignOtherUser";
import unAssignOtherUser from "../../../../utils/tasks/unAssignOtherUser";

interface AssignUserBtnProps {
    taskId: string | number;
}

export default function AssignUserBtn({ taskId }: AssignUserBtnProps): ReactNode {

    const [open, setOpen] = useState<boolean>(false);
    const [users, setUsers] = useState<Array<User>>([]);
    const [loading, setLoading] = useState<boolean>(true);

    const { user } = useContext(AuthContext) as any;

    if (!user?.isAdmin) return null;

    useEffect(() => {
        (async () => {
            setLoading(true);

            const result = await getAllUser();

            if (result.status !== 200 || !Array.isArray(result.data)) {
                console.error("Erreur lors du chargement des utilisateurs", result);
                return;
            }

            const usersData = await Promise.all(
                result.data.map(async (id: number): Promise<User | null> => {
                    const res = await getUserById(id);

                    if (res.status === 200) {
                        return res.data as User;
                    }

                    return null;
                })
            );

            setUsers(usersData.filter((user): user is User => user !== null));
            setLoading(false);
        })();
    }, []);

    const isUserAssigned = (u: User): boolean =>
        u.tasks.some(t => t.id === taskId);

    const handleAssign = async (selectedUser: User) => {
        await assignOtherUser(taskId as number, selectedUser.id);
        setOpen(false);
    };

    const handleUnassign = async (selectedUser: User) => {
        await unAssignOtherUser(taskId as number, selectedUser.id);
        setOpen(false);
    };

    return <>
        <Button variant={"default"} onClick={() => setOpen(true)}>Assigner</Button>

        <Modal open={open} onClose={() => setOpen(false)} title={"Assigner un utilisateur à cette tâche"}>
            <div className={styles.usersList}>
                {loading ? <Loading /> : users.map((user: User, index) => (
                    <div key={index} className={styles.userCard}>
                        <p className={styles.userName}>
                            {user.name} {user.lastname}
                        </p>

                        {isUserAssigned(user) ? (
                            <Button variant={"danger"} onClick={() => handleUnassign(user)}>
                                Désassigner
                            </Button>
                        ) : (
                            <Button onClick={() => handleAssign(user)}>
                                Assigner
                            </Button>
                        )}
                    </div>
                ))}
            </div>
        </Modal>
    </>
}