"use client";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useSessionStore } from "@store/Sesion.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import LocalPoliceOutlinedIcon from "@mui/icons-material/LocalPoliceOutlined";
import { useAlert } from "@store/Alert.Store";
import { useEffect, useState } from "react";
import { findCollaboratorsById, updateCollaboratorRoles } from "../../Collaborators.Service";
import { CompanyEmployeesView, EmployeeRoles } from "@models/Collaborators.model";
import MaterialAlert from "@mui/material/Alert";
import TriSwitch from "@core/app/components/TriSwitch/TriSwitch";

type UrlData = {
    id: string;
    cid: string;
};

export default function OrganizationService() {
    const data = useParams<UrlData>();
    const id = data.id;
    const cid = data.cid;
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const location = useLocationStore();
    const alert = useAlert();

    const [isFirstRender, setIsFirstRender] = useState(true);
    const [role, setRole] = useState<string>("");
    const [rolesIndex, setRolesIndex] = useState<Map<string, string>>(new Map<string, string>());

    const [collaborator, setCollaborator] = useState<CompanyEmployeesView>();
    const [collaboratorName, setCollaboratorName] = useState<string>("");
    const [, setCollaboratorUserId] = useState<string>("");
    const [, setCollaboratorAvatar] = useState<string>("");

    useEffect(() => {
        const rolesIndexMap = new Map<string, string>();
        rolesIndexMap.set("Administrador", "admin,employee");
        rolesIndexMap.set("Colaborador", "employee");
        setRolesIndex(rolesIndexMap);

        eventHandler.setEventType(EVENT_TYPES.SLEEP);
    }, []);

    useEffect(() => {
        if (isFirstRender) {
            setIsFirstRender(false);
        } else {
            handleRoleChange(); // Solo se ejecutará después de la primera vez
        }
    }, [role]);

    useEffect(() => {
        location.clear();

        location.add({
            url: "/admin/org/profile/" + id + "/collaborators",
            title: "Colaboradores",
            icon: null,
        });

        location.add({
            url: "/admin/org/profile/" + id + "/collaborators" + "/" + cid,
            title: collaboratorName,
            icon: <AccountCircleOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "/admin/org/profile/" + id + "/collaborators",
            title: "Rol del colaborador",
            icon: <LocalPoliceOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, [collaboratorName]);

    useEffect(() => {
        loadCollaborator();
    }, []);

    const loadCollaborator = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        findCollaboratorsById({ id: cid })
            .then((collaborator) => {
                if (collaborator === null) {
                    return;
                }
                setCollaborator(collaborator);
                setCollaboratorName(collaborator.fullName);
                setCollaboratorUserId(collaborator.userId);
                setCollaboratorAvatar(collaborator.avatar);
                setRole(getRoleValue(collaborator.roles));
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const getRolesByName = (name: EmployeeRoles): EmployeeRoles[] => {
        const index = rolesIndex.get(name);
        if (!index) {
            return [];
        }

        const returnRoles: EmployeeRoles[] = [];

        index.split(",").forEach((role) => {
            returnRoles.push(role as EmployeeRoles);
        });

        return returnRoles;
    };

    const getRoleValue = (roles: EmployeeRoles[] | undefined): string => {
        if (!roles) {
            return "";
        }

        if (roles.includes(EmployeeRoles.ADMIN)) {
            return "Administrador";
        } else if (roles.includes(EmployeeRoles.EMPLOYEE)) {
            return "Colaborador";
        } else {
            return "";
        }
    };

    const handleRoleChange = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        if (!collaborator) {
            eventHandler.setEventType(EVENT_TYPES.SLEEP);
            return;
        }

        const dbRole = getRoleValue(collaborator.roles);

        if (dbRole === role) {
            eventHandler.setEventType(EVENT_TYPES.SLEEP);
            return;
        }

        updateCollaboratorRoles({
            employeeId: cid,
            companyId: id,
            sessionUser: SessionInfo.userId,
            roles: getRolesByName(role as EmployeeRoles),
        })
            .finally(() => {
                alert.showSuccess("Rol actualizado");
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Location />
            <div
                style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px" }}
            >
                <MaterialAlert sx={{ marginBottom: "10px" }} severity="info">
                    <p>
                        Desde aquí puedes gestionar el rol de un colaborador, asignando permisos
                        avanzados con el rol de Administrador o permisos básicos con el rol de
                        Colaborador.
                    </p>
                    <p>
                        <strong>Administrador:</strong> Puede hacer todo lo que hace un colaborador,
                        pero tambien puede modificar el perfil de la organización y todo lo
                        relacionado con ella.
                    </p>
                    <p>
                        <strong>Colaborador:</strong> Los colaboradores pueden definir sus horarios,
                        administrar sus turnos, responder sus mensajes.
                    </p>
                </MaterialAlert>
                <TriSwitch
                    option1="Administrador"
                    option2="Colaborador"
                    value={role}
                    onChange={(value: string) => {
                        setRole(value);
                    }}
                />
            </div>

            <div style={{ marginBottom: "10px" }}>&nbsp;</div>
        </>
    );
}
