import React, { useState, useEffect, useContext } from "react";
import { useCookies } from "react-cookie";
import { useNavigate } from "react-router-dom";
import classes from "../assets/styles/adminPanel.module.scss";
import { UserData } from "../context";
import { getListUserApi, editUserApi, addUserApi, removeUserApi, editUserPass } from "../hooks/api/profileApi.js";
import { verifyUser } from "../hooks/services/profile.js";
import DefaultModal from "../components/DefaultModal.jsx";
import EditUserAdminPanel from "../components/bodyModal/EditUserAdminPanel.jsx";
import MyButton from "../components/MyButton.jsx";
import CheckModal from "../components/CheckModal.jsx";


const AdminPanel = () => {
    const navigate = useNavigate();
    const [cookies, setCookies] = useCookies(["user"]);
    const {user, setUser, userRef} = useContext(UserData);
    const [listUser, setListUser] = useState([]);

    const [email, setEmail] = useState("");
    const [firstName, setFirstName] = useState("");
    const [id, setId] = useState(false);
    const [isAdmin, setIsAdmin] = useState(false);
    const [isTeacher, setIsTeacher] = useState(false);
    const [lastName, setLastName] = useState("");
    const [login, setLogin] = useState("");
    const [phone, setPhone] = useState("");
    const [pass, setPass] = useState("");

    useEffect(() => {
        async function getListUser() {
            const responseListUser = await getListUserApi(cookies.token);

            if (
                responseListUser.status === 200
            ) {
                setListUser(responseListUser.data)
            }
            else if (
                responseListUser.status === 401
            ) {
                // navigate("/enter")
                setUser(false)
            }
            else {
                console.log(responseListUser)
            }
        }

        getListUser()
    }, []);

    function clearState() {
        setEmail("")
        setFirstName("")
        setId("")
        setIsAdmin("")
        setIsTeacher("")
        setLastName("")
        setLogin("")
        setPhone("")
        setPass("")
    };

    async function addUser() {
        const currentState = {
            email: email,
            first_name: firstName,
            id: id,
            is_admin: isAdmin,
            is_teacher: isTeacher,
            last_name: lastName,
            login: login,
            phone: phone
        }
        const response = await addUserApi(cookies.token, currentState)
        
        if (response.status === 200) {
            setListUser([...listUser, currentState])

            if (pass) {
                await editUserPass(cookies.token, login, pass);
            }
        }
        else if (
            response.status === 401
        ) {
            // navigate("/enter")
            setUser(false)
        }
        else {
            console.log(response)
        }
        clearState()
    };

    async function editUser() {
        const currentState = {
            email: email,
            first_name: firstName,
            id: id,
            is_admin: isAdmin,
            is_teacher: isTeacher,
            last_name: lastName,
            login: login,
            phone: phone
        };
        const response = await editUserApi(cookies.token, currentState);

        if (response.status === 200) {
            setListUser(listUser.map(item => item.id === id ? currentState : item));

            if (pass) { 
                await editUserPass(cookies.token, login, pass);
            };
        }
        else if (
            response.status === 401
        ) {
            // navigate("/enter")
            setUser(false)
        }
        else {
            console.log(response)
        }
        clearState();
    };

    function openUser(user) {
        setEmail(user.email)
        setFirstName(user.first_name)
        setId(user.id)
        setIsAdmin(user.is_admin)
        setIsTeacher(user.is_teacher)
        setLastName(user.last_name)
        setLogin(user.login)
        setPhone(user.phone)
    }

    async function removeUser(login) {
        const response = await removeUserApi(cookies.token, login)

        if (response.status === 200) {
            setListUser(listUser.filter(item => item.login !== login))
        }
        else if (
            response.status === 401
        ) {
            // navigate("/enter")
            setUser(false)
        }
        else {
            console.log(response)
        }
    }

    return (
        <div className={classes.main}>
            <div className={classes.wrapper}>
                <div className={classes.admin}>
                    {/* <div className={classes.admin__linkProfile}>
                        <span onClick={() => navigate("/profile")}>Профиль</span>
                    </div> */}
                    <div className={classes.admin__wrapper}>
                        <div className={classes.admin__wrapper__header}>
                            <h3>Пользователи</h3>
                            <MyButton 
                                text={"Создать пользователя"} 
                                class={"main__green"} 
                                toggle={"modal"} 
                                target={"#adminModal"}
                            />
                        </div>
                        <div className={classes.admin__wrapper__body}>
                            <div className={classes.admin__wrapper__body__columns}>
                                <div className={classes.admin__wrapper__body__columns__wrapper}>
                                    <div className={classes.admin__wrapper__body__columns__item}>Логин</div>
                                    <div className={classes.admin__wrapper__body__columns__item}>Фамилия</div>
                                    <div className={classes.admin__wrapper__body__columns__item}>Email</div>
                                    <div className={classes.admin__wrapper__body__columns__item}>Учитель</div>
                                    <div className={classes.admin__wrapper__body__columns__item}>Администратор</div>
                                </div>
                            </div>
                            <div className={classes.admin__wrapper__body__users}>
                                {listUser.map(item => 
                                    <div className={classes.admin__wrapper__body__users__item} key={item.id}>
                                        <div className={classes.admin__wrapper__body__users__item__wrapper}>
                                            <div 
                                                className={classes.admin__wrapper__body__users__item__link} 
                                                data-bs-toggle="modal" data-bs-target={`#adminModal`}
                                                onClick={() => openUser(item)}
                                            >
                                                {item.login}
                                            </div>
                                            <div className={classes.admin__wrapper__body__users__item__info}>
                                                {item.last_name ? item.last_name : '-'}
                                            </div>
                                            <div className={classes.admin__wrapper__body__users__item__info}>
                                                {item.email ? item.email : '-'}
                                            </div>
                                            <div className={classes.admin__wrapper__body__users__item__info}>
                                                {
                                                    item.is_teacher ? 
                                                    <i class="fa-solid fa-circle-check" style={{color: "rgb(150, 209, 158)"}}></i> : 
                                                    <i class="fa-solid fa-circle-xmark" style={{color: "rgb(235, 130, 130)"}}></i>
                                                }
                                            </div>
                                            <div className={classes.admin__wrapper__body__users__item__info}>
                                                {
                                                    item.is_admin ? 
                                                    <i class="fa-solid fa-circle-check" style={{color: "rgb(150, 209, 158)"}}></i> : 
                                                    <i class="fa-solid fa-circle-xmark" style={{color: "rgb(235, 130, 130)"}}></i>}
                                            </div>
                                            <div className={classes.admin__wrapper__body__users__item__remove}>
                                                <i class="fa-solid fa-trash" data-bs-toggle="modal" data-bs-target={`#checkModal${item.id}`}></i>
                                            </div>
                                            <CheckModal 
                                                postfix={item.id}
                                                message={`Вы хотетите удалить пользователя <${item.login}>?`} 
                                                action={{
                                                    execute: () => removeUser(item.login), 
                                                    cancel: () => {}
                                                }}
                                            />
                                        </div>   
                                    </div>
                                )}
                                <DefaultModal 
                                    name={"adminModal"}
                                    BodyModal={
                                        <EditUserAdminPanel
                                            id={id}
                                            email={email}
                                            firstName={firstName}
                                            isAdmin={isAdmin}
                                            isTeacher={isTeacher}
                                            lastName={lastName}
                                            login={login}
                                            phone={phone}
                                            setEmail={setEmail}
                                            setFirstName={setFirstName}
                                            setIsAdmin={setIsAdmin}
                                            setIsTeacher={setIsTeacher}
                                            setLastName={setLastName}
                                            setLogin={setLogin}
                                            setPhone={setPhone} 
                                            pass={pass}
                                            setPass={setPass}
                                        />
                                    } 
                                    btn={[
                                        {text: id ? "Изменить" : "Сохранить", dismiss: "modal", class: "main__green", action: id ? () => editUser() : () => addUser()},
                                        {text: "Отмена", dismiss: "modal", class: "main__white", action: () => clearState()}
                                    ]}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default AdminPanel;