import { useEffect, useRef, useState } from 'react';
import { useWindowWidth } from '../hooks/use-window-width';
import PHXFuncGetCookieSession from '../../Func/getCookieSession';
import saveCookiesClient from '../../Func/saveCookiesClient';
import React from 'react';
import { classNames } from '../../types';
import { PHXCard } from '../../Card';
import QuickAction from '../quick-action/quick-action';
import { useLoading } from '../../LoadingProvider';
export default function LeftHeaderSection({ checkLogoHeader, currSchoolId, perCodes, schools, topMenuLogoFromEnv, }) {
    const isMultiSchool = schools.length > 1;
    const wrapperRef = useRef(null);
    const windowWidth = useWindowWidth();
    const [show, setShow] = useState(false);
    const { setLoading: setLoadingGlobal } = useLoading();
    const currSchool = schools.find((school) => school.id === currSchoolId);
    const handleSwitchSchool = async (newSchoolId) => {
        var _a, _b;
        setShow(false);
        setLoadingGlobal(true);
        const currentSession = PHXFuncGetCookieSession();
        const userInfo = currentSession === null || currentSession === void 0 ? void 0 : currentSession.user_info;
        const nextSchool = schools.find((school) => school.id === newSchoolId);
        if (userInfo) {
            try {
                const newSchoolId = nextSchool === null || nextSchool === void 0 ? void 0 : nextSchool.id;
                const schoolIdCurrent = userInfo.school_id;
                const currentSchool = userInfo.school;
                if (newSchoolId && newSchoolId !== schoolIdCurrent) {
                    const res = await fetch('/api/authenticate/refresh-token-switch-school', {
                        method: 'POST',
                        body: JSON.stringify({
                            newUserId: nextSchool === null || nextSchool === void 0 ? void 0 : nextSchool.userId,
                            tenantId: newSchoolId,
                        }),
                        credentials: 'include',
                    });
                    const data = await res.json();
                    const userInfoNew = {
                        ...userInfo,
                        school_id: newSchoolId,
                        id: nextSchool === null || nextSchool === void 0 ? void 0 : nextSchool.userId,
                        school: {
                            ...currentSchool,
                            school_name: {
                                group_id: (_a = nextSchool === null || nextSchool === void 0 ? void 0 : nextSchool.school_name) === null || _a === void 0 ? void 0 : _a.group_id,
                            },
                            school_name_id: (_b = nextSchool === null || nextSchool === void 0 ? void 0 : nextSchool.school_name) === null || _b === void 0 ? void 0 : _b.id,
                        },
                    };
                    saveCookiesClient({
                        value: {
                            ...currentSession,
                            user_info: userInfoNew,
                            access_token: data.token,
                        },
                    });
                    window.location.href = '/dashboard';
                }
            }
            catch (error) {
                console.error(error);
            }
            finally {
                setLoadingGlobal(false);
            }
        }
    };
    useEffect(() => {
        const handleClickOutside = (event) => {
            var _a;
            if (wrapperRef.current && !((_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a.contains(event.target))) {
                setShow(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [wrapperRef]);
    return (React.createElement("div", { className: 'relative flex items-center gap-x-2' },
        React.createElement("div", { ref: wrapperRef },
            React.createElement("button", { className: classNames('flex items-center gap-x-1.5 rounded-lg px-1 py-1 text-xs font-medium text-gray-900', show ? 'bg-white' : '', isMultiSchool ? 'cursor-pointer' : 'cursor-default'), onClick: () => {
                    if (isMultiSchool) {
                        setShow(!show);
                    }
                }, type: 'button' },
                React.createElement("img", { className: 'h-5 w-5', src: checkLogoHeader || topMenuLogoFromEnv }),
                React.createElement("p", { className: 'max-w-[calc(100vw-220px)] truncate sm:w-fit' }, currSchool === null || currSchool === void 0 ? void 0 : currSchool.name),
                isMultiSchool && (React.createElement("svg", { className: classNames(' transition-all', show ? '-rotate-180' : ''), fill: 'none', height: '16', viewBox: '0 0 16 16', width: '16', xmlns: 'http://www.w3.org/2000/svg' },
                    React.createElement("path", { clipRule: 'evenodd', d: 'M4.57576 6.77535C4.81007 6.54103 5.18997 6.54103 5.42429 6.77535L8.20002 9.55108L10.9758 6.77535C11.2101 6.54103 11.59 6.54103 11.8243 6.77535C12.0586 7.00966 12.0586 7.38956 11.8243 7.62387L8.62429 10.8239C8.38997 11.0582 8.01007 11.0582 7.77576 10.8239L4.57576 7.62387C4.34145 7.38956 4.34145 7.00966 4.57576 6.77535Z', fill: '#6B7280', fillRule: 'evenodd' })))),
            show && (React.createElement("div", { className: 'absolute top-8 inline-block w-[calc(100vw-45px)] sm:w-max' },
                React.createElement(PHXCard, { primaryHeader: true, title: 'Ch\u1ECDn tr\u01B0\u1EDDng' },
                    React.createElement("div", { className: 'flex max-h-[400px] flex-col gap-y-1 overflow-y-auto' }, schools.map((school) => {
                        const isActive = currSchoolId === school.id;
                        return (React.createElement("button", { key: school.id, className: classNames('flex w-full min-w-full items-center justify-between rounded-lg p-2 text-left sm:w-max', isActive ? 'bg-[#EBEBEB]' : 'hover:bg-[#EBEBEB]'), onClick: () => handleSwitchSchool(school.id), type: 'button' },
                            React.createElement("div", { className: 'flex min-w-0 items-center gap-x-2' },
                                React.createElement("img", { className: 'h-[22px] w-[22px] shrink-0', src: school.logo || topMenuLogoFromEnv }),
                                React.createElement("span", { className: 'whitespace-normal break-words text-xs text-gray-900 sm:whitespace-nowrap' }, school.name)),
                            isActive && (React.createElement("svg", { className: 'ml-4 mr-1 shrink-0', fill: 'none', height: '8', viewBox: '0 0 12 8', width: '12', xmlns: 'http://www.w3.org/2000/svg' },
                                React.createElement("path", { clipRule: 'evenodd', d: 'M11.0303 0.21967C11.3232 0.512563 11.3232 0.987437 11.0303 1.28033L4.53033 7.78033C4.23744 8.07322 3.76256 8.07322 3.46967 7.78033L0.21967 4.53033C-0.0732233 4.23744 -0.0732233 3.76256 0.21967 3.46967C0.512563 3.17678 0.987437 3.17678 1.28033 3.46967L4 6.18934L9.96967 0.21967C10.2626 -0.0732233 10.7374 -0.0732233 11.0303 0.21967Z', fill: '#111827', fillRule: 'evenodd' })))));
                    })))))),
        windowWidth >= 1024 && React.createElement(QuickAction, { currSchoolName: (currSchool === null || currSchool === void 0 ? void 0 : currSchool.name) || '', perCodes: perCodes })));
}
//# sourceMappingURL=left-heder-section.js.map