"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 StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import { useEffect, useState } from "react";
import { findCollaboratorsById, validateHostCollaborator } from "../Collaborators.Service";
import Avatar from "@components/Avatar/Avatar";
import { CompanyEmployeesView } from "@models/Collaborators.model";
import MaterialAlert from "@mui/material/Alert";
import Button from "@components/Button/Button";
import ButtonPanel, { ButtonPanelItem } from "@core/app/components/ButtonPanel/ButtonPanel";

import SaveAsOutlinedIcon from "@mui/icons-material/SaveAsOutlined";
import TodayOutlinedIcon from "@mui/icons-material/TodayOutlined";
import AssignmentIndOutlinedIcon from "@mui/icons-material/AssignmentIndOutlined";
import CategoryOutlinedIcon from "@mui/icons-material/CategoryOutlined";
import DateRangeOutlinedIcon from "@mui/icons-material/DateRangeOutlined";
import AutoDeleteIcon from '@mui/icons-material/AutoDeleteOutlined';
import EventAvailableOutlinedIcon from '@mui/icons-material/EventAvailableOutlined';

import dayjs from "dayjs";
import "dayjs/locale/es";
dayjs.locale("es");

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 { goTo } = useNavigation();

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

    const buttons: Array<ButtonPanelItem> = [
        {
            icon: <SaveAsOutlinedIcon />,
            text: "Editar",
            onClick: () => {
                goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/edit");
            },
        },
        {
            icon: <TodayOutlinedIcon />,
            text: "Turnos",
            onClick: () => {
                goTo(
                    "/admin/org/profile/" +
                        id +
                        "/appointments/" +
                        encodeURIComponent(dayjs(new Date()).clone().startOf("day").toISOString())
                );
            },
        },
        {
            icon: <AssignmentIndOutlinedIcon />,
            text: "Roles",
            onClick: () => {
                goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/roles");
            },
        },
        {
            icon: <CategoryOutlinedIcon />,
            text: "Servicios",
            onClick: () => {
                goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/services");
            },
        },
        {
            icon: <DateRangeOutlinedIcon />,
            text: "Horarios",
            onClick: () => {
                goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/schedules");
            },
        },
        {
            icon: <AutoDeleteIcon />,
            text: "Restricciones",
            onClick: () => {
                goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/disabled");
            },
        },
        {
            icon: <EventAvailableOutlinedIcon />,
            text: "Excepciones",
            onClick: () => {
                goTo("/admin/org/profile/" + id + "/collaborators/" + cid + "/overrides");
            },
        },
    ];

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
    }, []);

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

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

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

        location.add({
            url: "/admin/org/services",
            title: collaboratorName,
            icon: (
                <Avatar
                    name={collaboratorName}
                    size="super-small"
                    border="none"
                    style={{ marginRight: "10px" }}
                    src={collaboratorAvatar}
                    alt={collaboratorName}
                />
            ),
        });
    }, [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);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const handleAgree = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        validateHostCollaborator({
            employeeId: cid,
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                loadCollaborator();
            })
            .catch((error) => {
                alert.showError(error.format());
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Location />
            <div
                style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px" }}
            >
                {collaborator && !collaborator.hostOk && (
                    <div
                        style={{
                            display: "flex",
                            flexDirection: "column",
                            alignContent: "center",
                            justifyContent: "center",
                            width: "100%",
                        }}
                    >
                        <MaterialAlert
                            severity="info"
                            sx={{
                                marginTop: "10px",
                                maxWidth: "680px",
                                marginLeft: "auto",
                                marginRight: "auto",
                            }}
                        >
                            <strong>Atención:</strong> Para que el colaborador pueda formar parte de
                            la organización primero debes confirmar y esperar a que el invitado
                            acepte la vinculación a la organización.
                        </MaterialAlert>

                        <Button
                            name="acceptButton"
                            width="100%"
                            text="Confirmar colaborador"
                            style={{
                                marginTop: "20px",
                                maxWidth: "680px",
                                marginLeft: "auto",
                                marginRight: "auto",
                            }}
                            onClick={handleAgree}
                        />
                    </div>
                )}

                {collaborator && collaborator.hostOk && !collaborator.fullOk && (
                    <>
                        <MaterialAlert
                            severity="info"
                            sx={{
                                marginTop: "10px",
                                maxWidth: "680px",
                                marginLeft: "auto",
                                marginRight: "auto",
                            }}
                        >
                            <strong>Atención:</strong> Para que el colaborador pueda formar parte de
                            la organización debes esperar a que el invitado acepte la vinculación a
                            la organización.
                        </MaterialAlert>
                    </>
                )}

                {collaborator && collaborator.fullOk && <ButtonPanel items={buttons} />}
            </div>

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