"use client";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import { useNavigation } from "@hooks/goto";
import { CompanyEmployeesView } from "@models/Collaborators.model";
import { loadCollaboratorsByCompanyId } from "./Collaborators.Service";
import { useAlert } from "@store/Alert.Store";
import CollaboratorItem from "@core/app/components/CollaboratorItem/CollaboratorItem";

type UrlData = {
    id: string;
};

export default function OrganizationProfile() {
    const data = useParams<UrlData>();
    const id = data.id;
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const alert = useAlert();
    const { goTo } = useNavigation();
    const [collaborators, setCollaborators] = useState<CompanyEmployeesView[]>([]);

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

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

        location.add({
            url: "/admin/org",
            title: "Mis organizaciones",
            icon: null,
        });

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

        location.add({
            url: "/",
            title: "Colaboradores",
            icon: null,
        });

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        loadCollaboratorsByCompanyId({ companyId: id })
            .then((response) => {
                setCollaborators(response);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    }, []);

    const handleCollaboratorClick = (collaboratorId: string) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        goTo("/admin/org/profile/" + id + "/collaborators/" + collaboratorId);
    };

    return (
        <>
            <Location />
            <div
                style={{ display: "flex", flexDirection: "column", marginTop: "20px", gap: "10px" }}
            >
                {collaborators.map((collaborator) => (
                    <CollaboratorItem
                        key={"collItem." + collaborator.id}
                        data={collaborator}
                        onClick={() => handleCollaboratorClick(collaborator.id)}
                    />
                ))}
            </div>
        </>
    );
}
