
"use client"

import { ServiceViewSettings } from "@/types/serviceAdmin";
import { makeStyles } from "tss-react/mui";
import { useTranslations } from "next-intl";
import useResponsive from "@/hooks/useResponsive";
import { useParams, useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { DOMAIN_TYPE, OPTION_LOGIN, PRINT_SETTING, UPLOAD_FILE_TYPES } from "@/lib/appConstant";
import { getAccountType, getCompanyDomain, getServicePath, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import { Fragment, useEffect, useState } from "react";
import StorageHelper from "@/lib/storeHelper";
import { STORAGE_KEYS } from "@/types/common";
import { useMounted } from "@/hooks/useMounted";
import { getAuthInfo } from "@/lib/redux/features/auth";
import { fetchViewerPublicToken, fetchViewerToken, getContentTypeViewer, getIsErrorViewerOnline, getPrintSettingViewer, getViewerToken, getWatermark } from "@/lib/redux/features/content";
import { detectBrowserVersion } from "@/lib/utils";
import { setShowBanner, setShowFooter, setShowHeader } from "@/lib/redux/features/layout";

type PropsType = { viewSettings?: ServiceViewSettings };

const useStyle = makeStyles()(() => ({
    fullSize: {
        width: '100%',
        height: 'calc(var(--vh, 1vh) * 100)',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        '& span': {
          fontWeight: 700,
          background: 'rgb(229, 57, 53)',
          color: '#fff',
          padding: '1rem'
        }
      },
      fullSizeEpubMobile: {
        width: '100VW',
        height: '100svh',
        overflowY: 'auto',
        '-webkit-overflow-scrolling': 'touch',
        border: 'none'
      },
      fullSizeEpubOldMobile: {
        width: '100VW',
        height: '100%',
        overflowY: 'auto',
        '-webkit-overflow-scrolling': 'touch',
        border: 'none'
      }
}));


export default function ViewOnlineRender(props: PropsType) {
    const t = useTranslations("");
    const dispatch = useAppDispatch();
    const router = useRouter();
    const mounted = useMounted();
    const { below768, getBelow768 } = useResponsive();

    
    const params = useParams();

    const { id, contentGroupId, viewToken } = params as { id?: string; contentGroupId?: string; viewToken?: string };
    
    const contentViewId = id || viewToken;

    const currentDomain = useAppSelector(getCompanyDomain);
    const servicePath = useAppSelector(getServicePath);
    const viewSettings = useAppSelector(getViewSettings);
    const accountType = useAppSelector(getAccountType);
    const viewerToken = useAppSelector(getViewerToken);
    const watermark = useAppSelector(getWatermark);
    const enablePrint = useAppSelector(getPrintSettingViewer);
    const isError: boolean = useAppSelector(getIsErrorViewerOnline);
    const authInfo = useAppSelector(getAuthInfo);
    const contentType = useAppSelector(getContentTypeViewer);

    const userStore = !servicePath || servicePath === '' ? currentDomain : servicePath;
    const isAuthen = StorageHelper.getLocalObject(userStore);
    const isToken = StorageHelper.getCookie(userStore);
    const beViewerHost = viewSettings.beViewerHost;
    // const below768 = useMedia('(max-width: 768px)');

    // const isMobile = Util.mobileCheck();
    // const isMobileTablet = Util.mobileAndTabletCheck();
    // const browserVersion = Util.detectBrowserVersion();
    
    const isMobile = null;
    const isMobileTablet = null;
    const browserVersion = detectBrowserVersion();    

    const [isOldVersion, setIsOldVersion] = useState(false);

    useEffect(() => {
        if (browserVersion.includes('Safari')) {
            const arr = browserVersion.split(' ');
            const currentVersion = arr[1];
            if (Number(currentVersion) <= 15) {
                setIsOldVersion(true);
            } else {
                setIsOldVersion(false);
            }
        }
    }, [browserVersion]);
    useEffect(() => {
        if (!isAuthen && !isToken && accountType !== OPTION_LOGIN.OPEN_TYPE) {
            StorageHelper.setSessionItem(STORAGE_KEYS.urlContentCallback, `${window.location.href}`);
            router.push(`${servicePath ? '/'+servicePath : ''}/`);
        }
    }, [isAuthen, isToken, accountType]);

    useEffect(() => {
        if (mounted) {
            if (accountType === OPTION_LOGIN.OPEN_TYPE) {
                    const request = {
                        contentId: contentViewId,
                        contentGroupId: contentGroupId
                    };
                    if (viewToken) {
                        dispatch(fetchViewerPublicToken({ tokenId: contentViewId }));
                    } else {
                        dispatch(fetchViewerToken(request));
                    }
            }
            if (accountType !== OPTION_LOGIN.OPEN_TYPE && isToken) {
                const request = {
                    contentId: contentViewId,
                    contentGroupId: contentGroupId
                };
                if (viewToken) {
                    dispatch(fetchViewerPublicToken({ tokenId: contentViewId }));
                } else {
                    dispatch(fetchViewerToken(request));
                }
            }
        }
    }, [mounted, isToken, accountType]);

    const { classes } = useStyle();

    const { watermarkContent: wmContent, color: wmColor, fontSize: wmFontSize, position: wmPosition, id: wmId } = watermark || {} as any;

    const isFullDomain = viewSettings.domainType === DOMAIN_TYPE.FULL_DOMAIN;

    const encodeWatermarkContent = encodeURIComponent(wmContent ? wmContent.replaceAll('&nbsp;', '') : '');
    const viewerSrc = `https://${beViewerHost}/viewer/${contentType}/index.html?token=${viewerToken}`;
    const viewerParams = `${enablePrint !== PRINT_SETTING.DO_NOT_ALLOW ? `&pr=${enablePrint}` : ''}${authInfo ? '&ui=' + authInfo.beUserId : ''}`;
    const watermarkURL = `&wt=${encodeWatermarkContent}${wmFontSize ? ('&ws=' + wmFontSize) : ''}${wmColor ? ('&wc=' + encodeURIComponent(wmColor)) : ''}${wmPosition ? ('&wp=' + wmPosition) : ''}`;
    const viewerURL = `${viewerSrc}${viewerParams}${!!wmId && contentType === UPLOAD_FILE_TYPES.PDF ? watermarkURL : ''}${'&tag=' + `${isFullDomain ? window.location.hostname : servicePath}`}`;

    useEffect(() => {
        if (viewerToken && viewerToken !== '') {
            const viewer: any = document.getElementById('urss-viewer');
            if (viewer) {
                viewer.focus();
                viewer.onload = (e) => {
                    viewer.focus();
                    viewer.contentWindow.focus();
                };
            }
        }
    }, [viewerToken]);

    useEffect(() => {
        const handleWindowResize = (e?: any) => {
            setTimeout(() => {
                const vh = window.innerHeight * 0.01;
                document.documentElement.style.setProperty('--vh', `${vh}px`);
            }, 300);
        };

        dispatch(setShowBanner(false));
        dispatch(setShowHeader(false));
        dispatch(setShowFooter(false));
        handleWindowResize();
        window.addEventListener('resize', handleWindowResize);

        return () => {
            window.removeEventListener('resize', handleWindowResize);
        };
    }, []);

    console.log('viewerURL: ', viewerURL);
    

    return (
        <Fragment>
            {
                viewerToken && viewerToken !== '' && beViewerHost && beViewerHost !== ''
        
                ? <iframe id={'urss-viewer'} className={contentType === 'epub'
                    ? (isMobile || isMobileTablet)
                    ? isOldVersion
                        ? classes.fullSizeEpubOldMobile
                        : classes.fullSizeEpubMobile
                    : classes.fullSize
                    : classes.fullSize}
                src={viewerURL} title="URSS View Book Online" 
                // allow="fullscreen *"
                allowFullScreen
                >
                </iframe>
                : null
            }
            {
                isError &&
                <span>
                    {t('label.notAllowViewBook')}
                </span>
            }
        </Fragment>
    );

}
