"use client"

import AppSidebar from "@/components/core/sidebar";
import { useMounted } from "@/hooks/useMounted";
import useResponsive from "@/hooks/useResponsive";
import { AUTHEN_TYPES, LAYOUT_SETTING, OPTION_LOGIN, SORT_FIELD_TYPE } from "@/lib/appConstant";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { getBodySetting, getCompanyDomain, getLayoutViewPage, getPageMargin, getServicePath, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import { makeStyles } from 'tss-react/mui';
import { getAllSort, loadAllSort } from "@/lib/redux/features/sort";
import { useEffect } from "react";
import { getPublicHashtag } from "@/lib/redux/features/hashtag";
import { useRouter, useSearchParams } from "next/navigation";
import { loadPublicContentGroups, setSortOrder } from "@/lib/redux/features/content";
import { getOpenSidebar, setShowBanner, setShowFooter, setShowHeader } from "@/lib/redux/features/layout";
import { doLogin, getAuthInfo, getIsAuthenticated, setCallstartAppWithCustomAuth } from "@/lib/redux/features/auth";
import StorageHelper from "@/lib/storeHelper";
import { getUserTrace } from "@/lib/utils";
import AppLoading from "../ui/loading";
import { STORAGE_KEYS } from "@/types/common";
import { setSearchRequest } from "@/lib/redux/features/search-page";

type PropsType = {
    children: React.ReactNode;
    sideBar?: boolean;
    header?: boolean;
    footer?: boolean;
    banner?: boolean;
    sort?: boolean;
    // isHomePage?: boolean;
    bodyMegreLayout?: boolean;
    autoIpLogin?: boolean;
    page?: "home" | "home-search" | "content-groups"
}

type MakeStylesType = {
    below768: boolean;
    isMegreLayout: boolean;
    bodySetting: any;
    pathname: any;
    pageMargin: any;
}

const useStyle = makeStyles<MakeStylesType>()((theme, { below768, isMegreLayout, bodySetting, pathname, pageMargin }) => {
    return (
    {
        body: {
            backgroundColor: `${bodySetting.backgroundColor}!important`,
            display: isMegreLayout ? '' : pathname.includes('subscription') ? 'block' : 'flex',
            flexDirection: 'row',
            flex: '1 0 0px',
            fontSize: below768 ? '12px' : '16px'
        },
        contain: {
            flex: '1 0 0px'
        },
        bodyLayout3: {
            marginLeft: below768 ? pathname.includes('profile') ? '10px' : '5px' : `${pageMargin.left}px`,
            marginRight: below768 ? pathname.includes('profile') ? '10px' : '5px' : `${pageMargin.right}px`
        }
    }
    );
});

export default function DefaultLayout(props: PropsType) {
    const { children, sideBar, header, footer, banner, sort, page, autoIpLogin } = props;
    const mounted = useMounted();
    const router = useRouter();
    const { below768, getBelow768 } = useResponsive();
    const dispatch = useAppDispatch();
    const searchParams = useSearchParams();

    const isOpenSidebar = useAppSelector(getOpenSidebar);
    const servicePath = useAppSelector(getServicePath);
    const domain = useAppSelector(getCompanyDomain);
    const listSorts = useAppSelector(getAllSort);
    const viewSettings = useAppSelector(getViewSettings);
    const bodySetting = useAppSelector(getBodySetting);
    const pageMargin = useAppSelector(getPageMargin);
    const layoutViewPage = useAppSelector(getLayoutViewPage);
    const isLoggedIn = useAppSelector(getIsAuthenticated);
    const isCallStartAppWithCustomAuth = useAppSelector((state) => state.auth.isCallStartAppWithCustomAuth);
    // const authInfo = useAppSelector(getAuthInfo);
    const UserID = searchParams.get('UserID');

    const userStore = !servicePath || servicePath === '' ? domain : servicePath;
    const token = StorageHelper.getCookie(userStore);
    const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
    const isHomeLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT.id;
    const loginSetting = viewSettings.settingLogin;
    const accountType = viewSettings.accountType;
    const pathname = window?.location ? window.location.pathname : '';
    
    
    const { classes } = useStyle({ below768, isMegreLayout, bodySetting, pageMargin, pathname: (mounted ? window.location.pathname : '') });

    const doAutoIpLogin = async () => {
        if (autoIpLogin) {
            const userTrace = await getUserTrace();
            const ip = userTrace.ip;
            const data = {
                client_ip_address: ip,
                company_domain: domain,
                path: servicePath,
            }
            dispatch(doLogin({ data, loginType: AUTHEN_TYPES.AUTO_IP, notShowMessage: true }));
        }
    };

    // useEffect(() => {
    //     const appMobileAuthToken = StorageHelper.getLocalItem(STORAGE_KEYS.appMobileAuthToken);
    //     if (isCallStartAppWithCustomAuth && UserID && accountType === OPTION_LOGIN.GAKKEN_ID && appMobileAuthToken && window && window.BEObj) {
    //         const request = {
    //             Token: appMobileAuthToken,
    //             CustomName: viewSettings.customName
    //         };
    //         window.BEObj.startAppWithCustomAuth(request);
    //         dispatch(setCallstartAppWithCustomAuth(false));
    //     }
    // }, [isCallStartAppWithCustomAuth, UserID]);
    useEffect(() => {
        if ((loginSetting || loginSetting === 0) && !token && domain && autoIpLogin) {
            doAutoIpLogin();
        }
    }, [loginSetting, domain]);
    useEffect(() => {
        if (accountType && page) {
            if (!isMegreLayout && domain && domain !== '') {
                dispatch(loadAllSort({ type: SORT_FIELD_TYPE.SORT_FIELD_HOME }));
            }
            if (page === "home") {
                if (bodySetting && (bodySetting.companyId || bodySetting.companyId === 0) && (bodySetting.serviceAdminId || bodySetting.serviceAdminId === 0)) {
                    dispatch(getPublicHashtag({ companyId: bodySetting.companyId, serviceAdminId: bodySetting.serviceAdminId }));
                }
            }
        }
    }, [domain, accountType]);
    useEffect(() => {
        if (page) {
            if (sort && listSorts && listSorts.length > 0) {
                const defaultSort = listSorts.find(item => item.isSortFieldDefault);
                if (page === "home-search" && defaultSort && defaultSort.field === 12) {
                    dispatch(setSortOrder({}));
                } else {
                    defaultSort && dispatch(setSortOrder({
                        sort: defaultSort.isAcsDefault,
                        sortField: defaultSort.field
                    }));
                }
            }
        }
    }, [listSorts]);
    

    // useEffect(() => {
    //     if (cacheSearchRequest) {
    //         dispatch(setSearchRequest(cacheSearchRequest.searchRequest));
    //     }
    // }, [cacheSearchRequest]);

    // useEffect(() => {
    //     if (!pathname.includes('search') && layoutViewPage === LAYOUT_SETTING.SEARCH_LAYOUT.id && !pathname.includes('/profile')) {
    //         history.push('/search');
    //         return;
    //     }
    //     if (pathname.includes('home-search') && layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id) {
    //         history.push('/search');
    //     }
    //     if (pathname.includes('home-search') && layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT.id) {
    //         dispatch(clearContents());
    //         setShowHomeSearch(true);
    //         // setIsDisableSort(true);
    //         below768 && setIsOpenSidebar(false);
    //     } else if (!pathname.includes('login')) {
    //         dispatch(clearContents());
    //         setShowHomeSearch(false);
    //         below768 && setIsOpenSidebar(false);
    //     }
    //     if (!pathname.includes('search')) {
    //         if (cacheSearchRequest) {
    //             setCacheSearchRequest();
    //         }
    //     } else {
    //         setSortOrder({});
    //     }
    //     if (!pathname.includes('order-entry')) {
    //         resetHtml();
    //     }
    // }, [pathname]);
    
    useEffect(() => {
        if (page && domain && domain !== '') {
            dispatch(loadPublicContentGroups({ isLoggedIn: isLoggedIn }));
        }
    }, [isLoggedIn, domain]);

    useEffect(() => {
        dispatch(setShowBanner(!!banner));
        dispatch(setShowHeader(!!header));
        dispatch(setShowFooter(!!footer));
    }, []);


    if (!viewSettings.accountType) {
        return <AppLoading/>;
    }

    console.log('viewSettings: ', viewSettings);
    
    
    
    return (
        <div role="main" className={`${classes.body} ${(!isOpenSidebar || below768 || !sideBar) && ' body-full '}`}>
            {
                isMegreLayout && classes.bodyLayout3
                ? <div className={`${isMegreLayout && !pathname.includes('/profile') && !pathname.includes('/subscription') ? classes.bodyLayout3 : classes.body}`}>
                    {
                        sideBar && !isMegreLayout &&
                        <AppSidebar listSorts={listSorts}/>
                    }
                    {children}
                </div>
                : <>
                    {
                        sideBar && !isMegreLayout &&
                        <AppSidebar listSorts={listSorts}/>
                    }
                    {children}
                </>
            }
        </div>
    );
}
