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

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

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

    const [collaboratorName, setCollaboratorName] = useState<string>("");
    const [collaboratorColor, setCollaboratorColor] = useState<string>("");

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

    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: "Editar",
            icon: <LocalPoliceOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        loadCollaborator();
    }, [collaboratorName]);

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            eventHandler.setEventType(EVENT_TYPES.LOADING);

            const data: UpdateEmployeeParams = {
                id: cid,
                calendarColor: collaboratorColor,
                sessionUser: SessionInfo.userId,
            };

            updateCollaborator(data)
                .then(() => {
                    alert.showSuccess("Información actualizada!");
                })
                .catch((error: ApiError) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    const loadCollaborator = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        findCollaboratorsById({ id: cid })
            .then((collaborator) => {
                if (collaborator === null) {
                    return;
                }

                setCollaboratorName(collaborator.fullName);
                setCollaboratorColor(collaborator.calendarColor);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    return (
        <>
            <Location />

            <MaterialAlert severity="info" sx={{ marginTop: "20px" }}>
                <b>Color del calendario:</b> el color será utilizado para representar los turnos de
                este colaborador en el calendario.
            </MaterialAlert>
            <PopoverPicker
                placeholder="Color del calendario"
                color={collaboratorColor}
                onChange={(color: string) => {
                    setCollaboratorColor(color);
                    eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
                }}
            />

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