"use client";
import { useEffect, useState, Suspense } from "react";
import { useSessionStore } from "@store/Sesion.Store";
import { useParams } from "next/navigation";
import Secure from "@components/Secure/Secure";
import OrganizationHeader from "@components/OrganizationHeader/OrganizationHeader";
import OrganizationContent from "@components/OrganizationContent/OrganizationContent";
import { loadOrganizationsById } from "./Org.Service";
import { MyOranizationsView } from "@models/Company.model";
import Menu from "@components/Menu/Menu";
import { useOrganizationHeaderStore } from "@core/Store/OrganizationHeader.Store";
import Content from "@core/app/components/Content/Content";
import SuspenseLoading from "@core/app/components/SuspendeLoading/SuspenseLoading";

type UrlData = {
    id: string;
};

export default function OrgLayout({ children }: { children: React.ReactNode }) {
    const [organization, setOrganization] = useState<MyOranizationsView | undefined>();
    const data = useParams<UrlData>();
    const organizationId = data.id;
    const SessionInfo = useSessionStore();
    const organizationHeader = useOrganizationHeaderStore();

    useEffect(() => {
        if (!SessionInfo.userId) {
            return;
        }

        loadOrganizationsById({ id: organizationId, sessionUser: SessionInfo.userId }).then(
            (organization) => {
                setOrganization(organization);
                organizationHeader.setHeaderColor(organization.headerColor);
                organizationHeader.setHeaderFontColor(organization.headerFontColor);
                organizationHeader.setHeaderFontShadowColor(organization.headerFontShadowColor);
            }
        );
    }, [SessionInfo.userId]);

    return (
        <>
            <Content>
                <Suspense fallback={<SuspenseLoading />}>
                    <Secure>
                        {organization && <OrganizationHeader data={organization} />}
                        <OrganizationContent>{children}</OrganizationContent>
                        <Menu />
                    </Secure>
                </Suspense>
            </Content>
        </>
    );
}
