"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 IconServices from "@mui/icons-material/CategoryOutlined";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import { useAlert } from "@store/Alert.Store";
import { useEffect, useState } from "react";
import {
    findCollaboratorsServices,
    updateCollaboratorsServices,
} from "../../Collaborators.Service";
import { CollaboratorServiceView, ServiceStatusItem } from "@models/Collaborators.model";
import MaterialAlert from "@mui/material/Alert";
import SelectableServiceItem from "@components/SelectebleServiceItem/SelectableServiceItem";

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

export default function CollaboratorService() {
    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 [collaborator, setCollaborator] = useState<CollaboratorServiceView>();
    const [serviceStatus, setServiceStatus] = useState<ServiceStatusItem[]>([]);

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

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

        if (!collaborator) {
            return;
        }

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

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

        location.add({
            url: "/admin/org/profile/" + id + "/collaborators",
            title: "Servicios activos",
            icon: <IconServices sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        loadServiceStatus();
    }, [collaborator]);

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

    useEffect(() => {
        if (eventHandler.eventType === EVENT_TYPES.SAVE) {
            updateCollaboratorsServices({
                companyId: id,
                employeeId: cid,
                services: serviceStatus,
                sessionUser: SessionInfo.userId,
            })
                .then(() => {
                    alert.showSuccess("Servicios actualizados!");
                })
                .catch((error) => {
                    alert.showError(error.format());
                })
                .finally(() => {
                    eventHandler.setEventType(EVENT_TYPES.SLEEP);
                });
        }
    }, [eventHandler.eventType]);

    const loadCollaboratorServices = () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        findCollaboratorsServices({
            companyId: id,
            employeeId: cid,
            sessionUser: SessionInfo.userId,
        })
            .then((collaborator) => {
                if (collaborator === null) {
                    return;
                }
                setCollaborator(collaborator);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const loadServiceStatus = () => {
        if (!collaborator) {
            return;
        }

        const loadServices: ServiceStatusItem[] = [];

        for (const service of collaborator.services) {
            loadServices.push({
                serviceId: service.id,
                active: service.active,
            });
        }

        setServiceStatus(loadServices);
    };

    const updateServiceStatus = (serviceId: string, active: boolean) => {
        if (!collaborator) {
            return;
        }

        const loadServices: ServiceStatusItem[] = [];

        for (const service of serviceStatus) {
            loadServices.push({
                serviceId: service.serviceId,
                active: service.serviceId === serviceId ? active : service.active,
            });
        }

        setServiceStatus(loadServices);
        eventHandler.setEventType(EVENT_TYPES.NEED_SAVE);
    };

    return (
        <>
            <Location />
            <div
                style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px" }}
            >
                <MaterialAlert sx={{ width: "100%" }} severity="info">
                    <strong>Servicios activos:</strong> para agregar o quitar un servicio,
                    simplemente presione el servicio. Es necesario{" "}
                    <strong>guardar los cambios</strong> al finalizar.
                </MaterialAlert>
                {collaborator &&
                    collaborator.services.map((service, index) => (
                        <SelectableServiceItem
                            data={service}
                            key={"selectableServiceItem." + index}
                            onChange={(serviceId: string, active: boolean) => {
                                updateServiceStatus(serviceId, active);
                            }}
                        />
                    ))}
            </div>

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