
import React, { useEffect, useState } from 'react';

import { useTranslations } from 'use-intl';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import { useMounted } from '@/hooks/useMounted';
import { AUTHEN_TYPES, BUTTON_ACTION, CONTENT_DETAIL_LAYOUT, CONTENT_GROUP_TYPE, DOMAIN_TYPE, LAYOUT_SETTING, mainColorMegreLayout, OPTION_LOGIN, PARAM_SERIES_CONTENT, PATTERNS, POSITION_CONFIG, POSITION_FAVORITE_BUTTON, SEARCH_FIELD, SETTING_LOGIN, USER_CONFIG } from '@/lib/appConstant';
import { getTextAlign, getUserTrace, hashMD5 } from '@/lib/utils';
import { STORAGE_KEYS } from '@/types/common';
import StorageHelper from '@/lib/storeHelper';
import { makeStyles } from 'tss-react/mui';
import useResponsive from '@/hooks/useResponsive';
import { getCompanyDomain, getContentDetailParams, getContentDetailSetting, getLayoutViewPage, getServicePath, getViewSettings } from '@/lib/redux/features/serviceAdmin';
import { doGetAuthInfo, getAuthInfo, getIsAuthenticated, getIsMobileApp } from '@/lib/redux/features/auth';
import { getIsPaymentError, getIsPaymentSuccess } from '@/lib/redux/features/payment';
import { fetchContentDetails, getContentInfo, getIsContentInfoLoad, getIsLoadContentDetailError, getIsLoadingGetContentDownloadId } from '@/lib/redux/features/content';
import { Row, Col, Skeleton } from 'antd';
import Chip from '@mui/material/Chip';
import TextField from '@mui/material/TextField';
import AppButton from '../ui/button/button';
import { Spinner } from 'reactstrap';
import LoginModal from '../modal/login-modal';
import LoginForm from '../auth/form/login-form';
import ModalConfirm from '../modal/modal-confirm';
import SubscriptionModal from '../modal/subscription-modal';
import SeriesContent from './series-content';
import { fetchSubscriptionList } from '@/lib/redux/features/subscription';
import CheckCircleOutlined from '@ant-design/icons/CheckCircleOutlined';
import CheckCircleFilled from '@ant-design/icons/CheckCircleFilled';
import IconButtonSearch from '../ui/icon/icon-button-search';
import IconBookMark from '../ui/icon/icon-book-mark';

type MakeStylesType = {
    below768: boolean;
    isMegreLayout: boolean;
    isFavouriteInfo: boolean;
    widthHeightIcon: any;
    style: any;
    styleButtonViewBook: any;
};
const useStyle = makeStyles<MakeStylesType>()((
    theme,
    { below768, isFavouriteInfo, isMegreLayout, widthHeightIcon, style, styleButtonViewBook }
) => {
    return (
        {
            itemMax: {
                maxWidth: 300,
                minWidth: 300,
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                display: 'inline-block'
            },
            coverCard: {
                display: 'flex',
                overflowX: 'auto',
                paddingBottom: '10px',
                color: 'black'
            },
            itemCard: {
                width: '300px',
                minWidth: 300,
                display: 'flex',
                flexDirection: 'column',
                backgroundColor: '#fff',
                border: '1px solid rgba(0, 0, 0, 0.125)',
                borderRadius: '0.25rem'
            },
            noImage: {
                marginBottom: '0.5rem',
                marginRight: '0.5rem',
                position: 'relative',
                overflow: 'hidden',
                '& img': {
                    maxHeight: 300,
                    maxWidth: 300,
                    objectFit: 'contain',
                    minWidth: 180,
                    border: '1px solid #d0d0d0'
                }
            },
            noImageLayout3: {
                marginBottom: '0.5rem',
                // marginRight: '4.5rem',
                position: 'relative',
                overflow: 'hidden',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                maxWidth: 550,
                // width: '90%',
                height: '100%',
                '& img': {
                    // width: '100%',
                    // maxHeight: '100%',
                    maxHeight: 300,
                    maxWidth: 300,
                    minWidth: 180,
                    objectFit: 'contain',
                    border: '1px solid #d0d0d0'
                },
                '& .favoriteIcon': {
                    top: 5,
                    right: below768 ? 5 : 0
                }
            },
            favoriteIcon: {
                position: 'absolute',
                top: 0,
                right: 0,
                color: '#F08828',
                margin: !isMegreLayout ? '4px 0.5rem' : (below768 ? '' : '0 5px 4px 5px'),
                fontSize: '1rem',
                background: '#fff',
                borderRadius: '50%',
                alignItems: 'center',
                justifyContent: 'center',
                display: 'flex',
                cursor: 'pointer',
                transition: 'all 0.3s ease-in-out',
                '&:hover': {
                    transform: 'scale(1.2)'
                },
                '& .wrap-icon': {
                    background: '#fff',
                    borderRadius: '50%',
                    border: '1.5px solid #999999',
                    width: isFavouriteInfo ? 28 : widthHeightIcon,
                    height: isFavouriteInfo ? 28 : widthHeightIcon,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }
            },
            favoriteIcon3: {
                position: 'absolute',
                top: 0,
                right: 0,
                color: '#fff',
                margin: !isMegreLayout ? '4px 0.5rem' : (below768 ? '' : '0 0.5rem 4px 0.5rem'),
                fontSize: '1rem',
                background: '#fff',
                borderRadius: '50%',
                alignItems: 'center',
                justifyContent: 'center',
                display: 'flex',
                cursor: 'pointer',
                transition: 'all 0.3s ease-in-out',
                '&:hover': {
                    transform: 'scale(1.2)'
                },
                '& .wrap-icon': {
                    background: '#00B27B',
                    borderRadius: '50%',
                    border: '1.5px solid #999999',
                    width: isFavouriteInfo ? 34 : widthHeightIcon,
                    height: isFavouriteInfo ? 34 : widthHeightIcon,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }
            },
            noFavoriteIcon3: {
                position: 'absolute',
                top: 0,
                right: 0,
                // color: '#F08828',
                margin: !isMegreLayout ? '4px 0.5rem' : (below768 ? '' : '0 0.5rem 4px 0.5rem'),
                fontSize: '1rem',
                background: '#fff',
                borderRadius: '50%',
                alignItems: 'center',
                justifyContent: 'center',
                display: 'flex',
                cursor: 'pointer',
                transition: 'all 0.3s ease-in-out',
                '&:hover': {
                    transform: 'scale(1.2)'
                },
                '& .wrap-icon': {
                    background: '#fff',
                    borderRadius: '50%',
                    border: '1.5px solid #999999',
                    width: isFavouriteInfo ? 34 : widthHeightIcon,
                    height: isFavouriteInfo ? 34 : widthHeightIcon,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }
            },
            wrapFavoriteIconLayout3: {
                width: '100%',
                display: 'flex',
                justifyContent: 'flex-end',
                alignItems: 'center'
            },
            favoriteIconLayout3: {
                color: '#fff',
                margin: '4px 0.5rem',
                fontSize: '1rem',
                background: '#fff',
                borderRadius: '50%',
                alignItems: 'center',
                justifyContent: 'center',
                display: 'flex',
                cursor: 'pointer',
                transition: 'all 0.3s ease-in-out',
                '&:hover': {
                    transform: 'scale(1.2)'
                },
                '& .wrap-icon': {
                    background: '#00B27B',
                    borderRadius: '50%',
                    border: '1.5px solid #999999',
                    width: isFavouriteInfo ? 34 : widthHeightIcon,
                    height: isFavouriteInfo ? 34 : widthHeightIcon,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }
            },
            noFavoriteIconLayout3: {
                // color: '#F08828',
                margin: '4px 0.5rem',
                fontSize: '1rem',
                background: '#fff',
                borderRadius: '50%',
                alignItems: 'center',
                justifyContent: 'center',
                display: 'flex',
                cursor: 'pointer',
                transition: 'all 0.3s ease-in-out',
                '&:hover': {
                    transform: 'scale(1.2)'
                },
                '& .wrap-icon': {
                    background: '#fff',
                    borderRadius: '50%',
                    border: '1.5px solid #999999',
                    width: isFavouriteInfo ? 34 : widthHeightIcon,
                    height: isFavouriteInfo ? 34 : widthHeightIcon,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }
            },
            registered: {
                position: 'absolute',
                top: 4,
                margin: '0 0.5rem',
                fontSize: '1.5rem',
                height: widthHeightIcon,
                width: widthHeightIcon,
                alignItems: 'center',
                justifyContent: 'center',
                display: 'flex'
            },
            bold: {
                fontWeight: 700
            },
            buttonView: {
                color: '#ffffff',
                fontWeight: 700,
                marginTop: '1rem'
            },
            iconButton: {
                marginRight: '0.5rem'
            },
            skeletonItemImage: {
                width: '100%',
                height: '100%',
                marginBottom: '0.5rem'
            },
            spin: {
                display: 'flex',
                justifyContent: 'center'
            },
            skeletonItemButton: {
                width: '115px!important',
                height: '45px'
            },
            modalStyle: {
                padding: 20,
                wordBreak: 'break-word',
                wordWrap: 'break-word',
                color: style.color || '',
                fontSize: style.fontSize || '',
                border: style.borderColor ? `1px solid ${style.borderColor}` : '',
                backgroundColor: `${style.backgroundColor || 'transparent'}!important`,
                '& div': {
                    wordBreak: 'break-word',
                    wordWrap: 'break-word'
                },
                minHeight: '100%'
            },
            smallFieldBox: {
                display: 'flex',
                flexDirection: 'row',
                flexWrap: 'wrap',
                justifyContent: 'center',
                alignItems: 'start',
                position: 'relative'
            },
            btnViewBook: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                minWidth: '50px',
                maxWidth: '100%',
                width: below768 ? '100%' : styleButtonViewBook.width ? styleButtonViewBook.width : (below768 ? '100%' : ''),
                border: '2px solid',
                boxShadow: 'none!important',
                backgroundColor: styleButtonViewBook.backgroundColor || '#e26042',
                color: styleButtonViewBook.color || '#fff',
                borderColor: styleButtonViewBook.borderColor || 'transparent',
                height: below768 ? 'auto' : styleButtonViewBook.height || 'auto',
                paddingTop: styleButtonViewBook.height ? 0 : 6,
                paddingBottom: styleButtonViewBook.height ? 0 : 6,
                '&:hover, &:focus, &:active': {
                    backgroundColor: `${styleButtonViewBook.hoverBackgroundColor || styleButtonViewBook.backgroundColor || '#e26042a8'}!important`,
                    color: `${styleButtonViewBook.hoverColor || styleButtonViewBook.color || '#fff'}!important`,
                    borderColor: `${styleButtonViewBook.hoverBorderColor || styleButtonViewBook.borderColor || 'transparent'}!important`
                }
            },
            contentOverlay: {
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: 10,
                padding: '4px'
            },
            noData: {
                textAlign: 'center',
                padding: '1rem',
                flex: '1 0 100%'
            },
            chip: {
                background: '#fff',
                backgroundColor: 'white',
                height: '28px',
                color: mainColorMegreLayout,
                fontSize: '12px',
                fontWeight: 'bold',
                border: '1px solid #d0d0d0'
            },
            wrapFlexCenter: {
                display: 'flex',
                alignItems: 'center'
            },
            contentImage: {
                display: 'flex',
                width: '100%',
                justifyContent: 'center',
                padding: below768 ? '0 10%' : ' 0 4rem 0 0',
                marginBottom: below768 ? '25px' : 0
            },
            contentInfo: {
                width: '100%',
                paddingLeft: '3rem',
                ['@media (max-width:960px)']: { // eslint-disable-line no-useless-computed-key
                    paddingLeft: 0
                }
            },
            field0: {
                fontSize: 18,
                fontWeight: 700,
                color: '#585757'
            },
            field1: {
                fontSize: 13,
                fontWeight: 400,
                color: '#585757'
            },
            field2: {
                fontSize: 13,
                fontWeight: 400,
                color: '#999999'
            },
            btnLoading: {
                opacity: 0.5
            }
        }
    )
});


const ContentDetailsRender = props => {
  const {
    isLoggedContentDirect,
    onSelectFavorite = () => {},
    showFavorite,
    // sessionActions: {
    //   login
    // },
    // paymentActions: {
    //   resetPaymentStatus,
    //   resetGakkenPaymentInfo,
    //   resetCreateOrderReceive
    // },
    // contentActions: {
    //   getDownloadContentId,
    //   resetLoadingDownloadContent
    // }
  } = props;

    const t = useTranslations("");
    const dispatch = useAppDispatch();
    const router = useRouter();
    const mounted = useMounted();
    const searchParams = useSearchParams();
    // const { id: contentId } = useParams() as { id: string };
    // const contentGroupId = Number(searchParams.get('contentGroupId'));
    
    const params = useParams();
    const contentId = params.contentId as string;
    const contentGroupId = Number(params.contentGroupId);

    const contentToken = searchParams.get('contentToken');

    // const imageContentRef = React.useRef();
    const { below768, getBelow768 } = useResponsive();

    const [sortFields, setSortFields] = useState<any[]>([]);
    const [longFields, setLongFields] = useState<any[]>([]);
    const [widthHeightIcon, setWidthHeightIcon] = useState<number>(28);
    const [isShowSubscription, setIsShowSubscription] = useState(false);
    const [showConfirmViewer, setShowConfirmViewer] = useState(false);
    const [showLoginFormModal, setShowLoginFormModal] = useState(false);
    const [isShowViewBook, setIsShowViewBook] = useState(false);
    const [showRegister, setShowRegister] = useState(false);
    // const [isFullSlotParam, setIsFullSlotParam] = useState(true);
    // const [showInfo, setShowInfo] = useState(false);
    // const [cacheGakkenPayment, setCacheGakkenPayment] = useState({});

    const [contentDetailId, setContentDetailId] = useState('');
    const [url, setUrl] = useState('');

    const isBEOStaging = !process.env.NEXT_PUBLIC_IS_BEO_STAGING
        ? process.env.NEXT_PUBLIC_IS_STAGING_SERVER : (process.env.NEXT_PUBLIC_IS_BEO_STAGING === 'true');

    const style = useAppSelector(getContentDetailSetting);
    const isPaymentSuccess = useAppSelector(getIsPaymentSuccess);
    const isPaymentError = useAppSelector(getIsPaymentError);
    const isMobileApp = useAppSelector(getIsMobileApp);
    const viewSettings = useAppSelector(getViewSettings);
    const servicePath = useAppSelector(getServicePath);
    const downloadContentIdApp = useAppSelector((state) => state.content.downloadContentObj);
    const isGettingDownloadContentIdApp = useAppSelector(getIsLoadingGetContentDownloadId);

    // Layout
    const contentInfo = useAppSelector(getContentInfo);
    const isLoaded = useAppSelector(getIsContentInfoLoad);
    const contentSetting = useAppSelector(getContentDetailParams);
    const isLoggedIn = !!useAppSelector(getIsAuthenticated);
    const domain = useAppSelector(getCompanyDomain);
    const isError = useAppSelector(getIsLoadContentDetailError);
    const layoutViewPage = useAppSelector(getLayoutViewPage);


    const urlGakkenPayment = useAppSelector((state) => state.payment.redirectUrl);
    const isLoadingGakkenInfo = useAppSelector((state) => state.payment.isLoadingGakkenInfo);
    const isCreateOrderReceive = useAppSelector((state) => state.payment.isCreateOrderReceive);
    const isRediectUrl = useAppSelector((state) => state.payment.isRediectUrl);
    const positionFavourite = viewSettings.contentSearchResultSettingResponse ? (viewSettings.contentSearchResultSettingResponse.buttonFavouritePosition ? viewSettings.contentSearchResultSettingResponse.buttonFavouritePosition : POSITION_FAVORITE_BUTTON.IMAGE) : POSITION_FAVORITE_BUTTON.IMAGE;

    const loginSetting = viewSettings.settingLogin;
    const showSubscriptionStatus = viewSettings.showSubscriptionStatus;
    const isOpenType = viewSettings.accountType === OPTION_LOGIN.OPEN_TYPE;
    const isNolayout = layoutViewPage === LAYOUT_SETTING.NO_LAYOUT.id;
    const isFullDomain = viewSettings.domainType === DOMAIN_TYPE.FULL_DOMAIN;
    const isRequireLogin = loginSetting === SETTING_LOGIN.LOGINREQUIRE.value;
    const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
    const isFavouriteInfo = positionFavourite === POSITION_FAVORITE_BUTTON.INFORMATION;
    const viewContentInfo = contentInfo.view === true || contentInfo.view === false ? contentInfo.view : true;
    // const queryURL = new URLSearchParams(search);

    const styleButtonViewBook = style.buttons && style.buttons.length > 0 ? style.buttons.filter(item => item.actionType === BUTTON_ACTION.VIEW_BOOK.id)[0] : {} as any;

    const allowViewBook = isLoggedIn || isOpenType || isNolayout;
    // const widthButton = viewSettings.contentSearchResultSettingResponse
    //   ? (viewSettings.contentSearchResultSettingResponse.width ? viewSettings.contentSearchResultSettingResponse.width : '')
    //   : '';

    const urlViewer = url + '/view-online/' + (contentInfo.id || contentDetailId) + `${contentGroupId ? '/' + contentGroupId : ''}`;

    const { classes } = useStyle({ below768, isFavouriteInfo, isMegreLayout, widthHeightIcon, style, styleButtonViewBook });
    useEffect(() => {
        const protocol = window.location.protocol;
        const hash = window.location.hash !== '' ? '#' : '';
        const port = window.location.port;
        const path = isFullDomain ? '' : '/' + servicePath;
        if (port) {
            setUrl(protocol + '//' + domain + ':' + port + path + hash);
        } else {
            setUrl(protocol + '//' + domain + path + hash);
        }
        scrollToTop();
    }, []);
    const scrollToTop = () => {
        window.scrollTo({ top: 0, left: 0, behavior: 'smooth' });
    };
    // useEffect(() => {
    //     if (isLoggedContentDirect) {
    //         dispatch(doGetAuthInfo());
    //     }
    // }, [isLoggedContentDirect]);
    useEffect(() => {
        if (contentGroupId) {
            const validate = /[a-z]/g;
            const format = validate.exec(contentGroupId.toString());
            if (format) {
                router.push(`${servicePath ? '/'+servicePath : ''}/`);
            }
        }
    }, [contentGroupId]);

    useEffect(() => {
        if (contentId) {
            const regex = PATTERNS.ELEMENT_ID;
            const validId = regex.test(contentId.toString());
            if (!validId) {
                if (isNolayout) {
                    setTimeout(() => {
                        router && router.push('/error-404');
                    }, 200);
                } else {
                    router.push(`${servicePath ? '/'+servicePath : ''}/`);
                }
            }
        }
        if (contentId && !contentGroupId && (allowViewBook || layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id || layoutViewPage === LAYOUT_SETTING.SEARCH_LAYOUT.id)) {
            handleLoadDetail({ contentId });
        }
    }, [contentId, allowViewBook]);

    useEffect(() => {
        if (isLoggedIn) {
            if (isShowViewBook && contentDetailId) {
                const windowReference = window.open(urlViewer);
                if (!windowReference) {
                setShowConfirmViewer(true);
                }
                setIsShowViewBook(false);
            }
        } else {
            setIsShowViewBook(false);
        }
    }, [isLoggedIn]);

    useEffect(() => {
        const cacheStorage = StorageHelper.getSessionObject(STORAGE_KEYS.cacheStorage);
        if (isLoggedIn && cacheStorage && cacheStorage.isShowViewBook) {
            if (contentId) {
                const windowReference = window.open(urlViewer);
                if (!windowReference) {
                setShowConfirmViewer(true);
                }
                setIsShowViewBook(false);
            }
            StorageHelper.removeSessionItem(STORAGE_KEYS.cacheStorage);
        }
    }, [isLoggedIn]);

    useEffect(() => {
        if (contentId && contentGroupId) {
            if (!isRequireLogin) {
                handleLoadDetail({ contentId, contentGroupId });
            } else {
                if (isLoggedIn) {
                handleLoadDetail({ contentId, contentGroupId });
                }
            }
        }
    }, [contentId, contentGroupId, allowViewBook, isRequireLogin, isLoggedIn]);

    useEffect(() => {
        if (!isLoggedIn) {
            if (isShowSubscription) {
                setIsShowSubscription(false);
            }
            if (showRegister) {
                setShowRegister(false);
            }
        }
    }, [isLoggedIn, isShowSubscription, showRegister]);
    useEffect(() => {
        if (contentToken) {
            if (isOpenType || isLoggedContentDirect || !isRequireLogin) {
                handleLoadDetail({ contentToken });
            }
        }
    }, [contentToken, isOpenType, isLoggedContentDirect, loginSetting]);
    useEffect(() => {
        let arraySortField: any[] = [];
        let arrayLongField: any[] = [];
        var count = 0;
        if (contentSetting && contentSetting.length > 0) {
            for (const item of contentSetting) {
                const displayField = { itemSetting: item, contentInfo, isFullWidth: false, isFullSlot: true, count };
                if (item.hasBox) {
                    arrayLongField = [...arrayLongField, displayField];
                } else {
                    arraySortField = [...arraySortField, displayField];
                }
            }
            setSortFields(arraySortField);
            setLongFields(arrayLongField);
        } else {
            setSortFields(arraySortField);
            setLongFields(arrayLongField);
        }
    }, [contentInfo]);

    useEffect(() => {
        if (isPaymentSuccess || isPaymentError) {
            handleLoadDetail({ contentId });
            // dispatch(resetGakkenPaymentInfo());
            // dispatch(resetPaymentStatus());
        }
    }, [isPaymentSuccess, isPaymentError]);

    useEffect(() => {
        if (urlGakkenPayment) {
        if (isRediectUrl) {
            window.open(`${urlGakkenPayment}`, '_self');
        } else {
        //    dispatch(resetCreateOrderReceive());
        }
        }
        if (!isCreateOrderReceive && urlGakkenPayment === '') {
        setShowRegister(false);
        }
    }, [urlGakkenPayment, isCreateOrderReceive]);

    // useEffect(() => {
    //     handleResizeScreen();
    // }, [imageContentRef.current]);

    // useEffect(() => {
    //     window.addEventListener('resize', handleResizeScreen);
    //     return () => {
    //     window.removeEventListener('resize', handleResizeScreen);
    //     };
    // }, []);

    useEffect(() => {
        if (downloadContentIdApp && window && window.BEObj) {
            // dispatch(resetLoadingDownloadContent());
            window.BEObj.openContent({
                DownloadID: downloadContentIdApp.downloadId,
                AuthID: downloadContentIdApp.authId,
                AuthName: downloadContentIdApp.authName,
                AuthKey: downloadContentIdApp.authKey,
                CustomName: downloadContentIdApp.customName,
                ShowAlertSB: false,
                ShowAlertNSB: false
            });
        }
    }, [downloadContentIdApp]);

    // const handleResizeScreen = () => {
    //     if (imageContentRef && imageContentRef.current && imageContentRef.current.clientWidth) {
    //     const width = imageContentRef.current.clientWidth;
    //     const height = imageContentRef.current.clientHeight;
    //     var size = height > width ? width * 0.08 : height * 0.08;
    //     if (size < 15) {
    //         size = 15;
    //     }
    //     if (size > 45) {
    //         size = 45;
    //     }
    //     setWidthHeightIcon(size);
    //     }
    // };

    const renderOverlayText = (contentGroupType) => {
        var label = '';
        switch (contentGroupType) {
        case CONTENT_GROUP_TYPE.NEW:
            label = t('label.newOverlay');
            break;
        case CONTENT_GROUP_TYPE.POPULAR:
            label = t('label.popularOverlay');
            break;
        case CONTENT_GROUP_TYPE.RECOMMEND:
            label = t('label.recommendOverlay');
            break;
        default:
            label = '';
        }
        if (label === '') {
            return null;
        }
        if (isMegreLayout) {
            return <span style={{ color: mainColorMegreLayout, fontWeight: below768 ? 'bold' : '' }}>{label}</span>;
        }
        return (<Chip size={'30px' as any} className={`${classes.chip}`} label={label} />);
    };
    const handleLoadDetail = ({ contentId, contentGroupId, contentToken }: { contentId?:string; contentGroupId?: number; contentToken?: any }) => {
        dispatch(fetchContentDetails({ contentId, contentGroupId, contentToken }));
    };
    const handleSetInnerHTML = (text: any) => {
        return (<span dangerouslySetInnerHTML={{ __html: text }} />);
    };
    const returnTemplateContentInfo = (searchField, itemSetting, contentInfo, isFullWidth, isFullSlot, count, className) => {
        if (!itemSetting.isShowLabel && (!contentInfo[searchField.dbKey] || contentInfo[searchField.dbKey] === '')) {
            return null;
        }
        return (
            <React.Fragment key={`key-detail-${searchField.dbKey}-${(new Date()).getTime()}`}>
                <Col
                    span={isFullWidth ? 24 : Number(itemSetting.size) * 2}
                    id={`key-detail-${searchField.dbKey}-${(new Date()).getTime()}`}
                    className={`mB-1 ${itemSetting.hasBox && 'has-box'} ${className}`}
                    style={below768 && itemSetting.hasBox ? { padding: '0 10px' } : {}}
                >
                {
                    ((itemSetting.isShowLabel && isMegreLayout) || !isMegreLayout) &&
                    <span >
                    {`${itemSetting.title}: `}
                    </span>
                }
                {
                    itemSetting.hasBox
                    ? <TextField variant={'outlined'} multiline type={'textarea'} value={contentInfo[searchField.dbKey]} />
                    : handleSetInnerHTML(contentInfo[searchField.dbKey])
                }
                </Col>
            </React.Fragment>
        );
    };
    const renderContentInfo = ({ itemSetting, contentInfo, isFullWidth, isFullSlot, count, index }) => {
        let className: any = null;
        if (isMegreLayout) {
            switch (index) {
                case 0:
                    className = classes.field0;
                    break;
                case 1:
                    className = classes.field1;
                    break;
                case 2:
                    className = classes.field2;
                    break;
                default:
                    className = classes.field1;
                    break;
            }
        }

        const searchField = getSearchField(itemSetting.field);
        if (searchField) {
            return returnTemplateContentInfo(searchField, itemSetting, contentInfo, isFullWidth, isFullSlot, count, className);
        }
    };

    const getSearchField = (field) => {
        switch (field) {
        case SEARCH_FIELD.TITLE.id:
            return SEARCH_FIELD.TITLE;
        case SEARCH_FIELD.AUTHOR.id:
            return SEARCH_FIELD.AUTHOR;
        case SEARCH_FIELD.KEYWORDS.id:
            return SEARCH_FIELD.KEYWORDS;
        case SEARCH_FIELD.TOC.id:
            return SEARCH_FIELD.TOC;
        case SEARCH_FIELD.DISTRIBUTOR.id:
            return SEARCH_FIELD.DISTRIBUTOR;
        case SEARCH_FIELD.DESCRIPTION.id:
            return SEARCH_FIELD.DESCRIPTION;
        case SEARCH_FIELD.PARAM_1.id:
            return SEARCH_FIELD.PARAM_1;
        case SEARCH_FIELD.PARAM_2.id:
            return SEARCH_FIELD.PARAM_2;
        case SEARCH_FIELD.PARAM_3.id:
            return SEARCH_FIELD.PARAM_3;
        case SEARCH_FIELD.PARAM_4.id:
            return SEARCH_FIELD.PARAM_4;
        case SEARCH_FIELD.PARAM_5.id:
            return SEARCH_FIELD.PARAM_5;
        default:
            return null;
        }
    };

    const showSubscriptionList = (contentGroupId: number) => {
        dispatch(fetchSubscriptionList({ contentGroupId: contentGroupId }));
        setIsShowSubscription(true);
    };
    const openViewOnline = (content: any, contentGroupId: number) => {
        setIsShowViewBook(true);
        if (allowViewBook) {
        window.open(urlViewer, '_blank');
        } else {
        setContentDetailId(content.id);
        setShowLoginFormModal(true);
        }
    };
    const cancelLoginModal = () => {
        setShowLoginFormModal(false);
        setIsShowViewBook(false);
    };
    // const handleLoginFormSubmit = async (data: any, authenType: any) => {
    //     setShowLoginFormModal(false);
    //     let request: any;
    //     if (authenType === AUTHEN_TYPES.EMAIL) {
    //     request = {
    //         password: hashMD5(data.password),
    //         rememberMe: data.rememberMe,
    //         email: data.email,
    //         loginType: AUTHEN_TYPES.EMAIL,
    //         loginRole: USER_CONFIG.USER.loginType,
    //         path: data.path
    //     };
    //     } else if (authenType === AUTHEN_TYPES.GOOGLE_LOGIN) {
    //         request = data;
    //     } else {
    //         const userTrace = await getUserTrace();
    //         const ip = userTrace.ip;
    //         request = {
    //             ip: ip,
    //             loginType: AUTHEN_TYPES.IP
    //         };
    //     }
    //     login(request);
    // };

    const getJustifyContent = (positionId: number) => {
        switch (positionId) {
        case POSITION_CONFIG.CENTER.id:
            return 'center';
        case POSITION_CONFIG.LEFT.id:
            return 'flex-start';
        case POSITION_CONFIG.RIGHT.id:
            return 'flex-end';
        default:
            return 'center';
        }
    };

    const renderButton = () => {
        return (
            <AppButton
                // primaryColor={'red'}
                className={`${classes.buttonView} ${classes.btnViewBook} ${isGettingDownloadContentIdApp && classes.btnLoading}`}
                onClick={() => {
                    if (isMobileApp) {
                        const request: any = {
                            contentGroupId: contentGroupId,
                            contentId: contentInfo.id
                        };
                        if (contentToken) {
                            request.contentDetailId = contentToken;
                            delete request.contentId;
                        }
                        if (!isGettingDownloadContentIdApp) {
                            // dispatch(getDownloadContentId(request));
                        }
                    } else if (allowViewBook) {
                        if (!contentInfo.isSubscriptionPlan || contentInfo.isRegistered) {
                            openViewOnline(contentInfo, contentGroupId);
                        } else {
                            showSubscriptionList(contentGroupId);
                        }
                    } else {
                        openViewOnline(contentInfo, contentGroupId);
                    }
                }}
            >
                {
                !isMobileApp && isMegreLayout && styleButtonViewBook.isShowIcon && styleButtonViewBook.icon && styleButtonViewBook.icon !== '' &&
                    
                    <span className={classes.iconButton}>
                        {/* <i className={styleButtonViewBook.icon}></i> */}
                        <IconButtonSearch value={styleButtonViewBook.icon}/>
                    </span>
                }
                {
                isMobileApp
                    ? isGettingDownloadContentIdApp
                        ? <Spinner/>
                        : t('label.download')
                    : (styleButtonViewBook.label && styleButtonViewBook.label !== ''
                        ? <span>{styleButtonViewBook.label}</span>
                        : t('label.displayBook')
                    )
                }
            </AppButton>
        );
    };

    const nameSeries = contentInfo[PARAM_SERIES_CONTENT[viewSettings.contentSearchResultSettingResponse?.paramSeriesContent]];

    if (isError) {
        return (
            <div className={classes.noData}>
                { t('text.noData') }
            </div>
        );
    } else {
        return (
            <div className={`${classes.modalStyle}`}>
                {
                    <>
                        {
                            isLoaded || !window.BEObj || isLoadingGakkenInfo
                            ? <div>
                                <Row>
                                    <Col span={24}>
                                        <Row>
                                            <Col span={8}>
                                                <div><Skeleton className={classes.skeletonItemImage} /></div>
                                            </Col>
                                            <Col span={16}>
                                                <div>
                                                    <h5><Skeleton /></h5>
                                                </div>
                                            </Col>
                                        </Row>
                                    </Col>
                                    <Col span={24} className={'text-left'} >
                                        <div><Skeleton className={classes.skeletonItemButton} /></div>
                                    </Col>
                                </Row>
                            </div>
                            : <Row>
                                <Col span={24} style={{ padding: isMegreLayout ? '0 10px' : '0 15px' }}>
                                    <div className={classes.smallFieldBox}>
                                    {
                                        isMegreLayout &&
                                        <Row gutter={6} style={{ width: '100%' }}>
                                            {/* content Image */}
                                            <Col span={12} style={{ width: '100%' }}>
                                                <div className={`${classes.contentImage}`}>
                                                    {/* <div ref={imageContentRef} className={classes.noImageLayout3}> */}
                                                    <div className={classes.noImageLayout3}>
                                                        <img src={contentInfo.beContentsId ? window.BEObj.getContentsURL({ cid: contentInfo.beContentsId, type: 2, staging: !!isBEOStaging, cdn: true }) : require('../../assets/img/no-image.png')} />
                                                        {
                                                            showSubscriptionStatus && contentInfo.isRegistered
                                                            ? <div className={`${classes.registered}`} title={t(contentInfo.isSubscriptionPlan ? 'label.subscribed' : 'label.free')}
                                                            style={{
                                                                right: (isLoggedIn && showFavorite) ? isMegreLayout ? 35 : widthHeightIcon * 1.2 : 0,
                                                                top: 10
                                                            }}>
                                                                <CheckCircleOutlined style={{ color: 'green', fontSize: isMegreLayout ? 26 : widthHeightIcon }}/>
                                                            </div>
                                                            : null
                                                        }
                                                        {
                                                        (below768 || (isLoggedIn && showFavorite && positionFavourite === POSITION_FAVORITE_BUTTON.IMAGE)) && (
                                                            <div
                                                                className={`${isMegreLayout ? contentInfo.isFavorite ? classes.favoriteIcon3 : classes.noFavoriteIcon3 : classes.favoriteIcon} favoriteIcon`}
                                                                onClick={() => onSelectFavorite(contentInfo.id, contentInfo.isFavorite)}
                                                            >
                                                                <div className="wrap-icon"
                                                                    style={{
                                                                    width: isMegreLayout ? below768 ? 29 : 28 : widthHeightIcon,
                                                                    height: isMegreLayout ? below768 ? 29 : 28 : widthHeightIcon
                                                                    }}
                                                                >
                                                                    {
                                                                        <IconBookMark isFavorite={!isMegreLayout && contentInfo.isFavorite} size={'15px'}/>
                                                                    }
                                                                </div>
                                                            </div>
                                                        )
                                                        }
                                                    </div>
                                                </div>
                                            </Col>
                                            {/* content Info */}
                                            <Col span={12} className={`${classes.wrapFlexCenter} ${classes.contentInfo}`}>
                                                <div className={'row'} style={{ flex: '1 0 0px', minWidth: 280 }} >
                                                    {
                                                        contentInfo.type && renderOverlayText(contentInfo.type) &&
                                                        <Col span={ !below768 && isFavouriteInfo ? 12 : 24 } className={`${!below768 && 'mB-1'} ${classes.wrapFlexCenter}`}>
                                                            {renderOverlayText(contentInfo.type)}
                                                        </Col>
                                                    }
                                                    {
                                                        below768 &&
                                                        <>
                                                            {
                                                            sortFields.map((item, index) => {
                                                                if (index === 0 || index === 1) {
                                                                return renderContentInfo({ ...item, index });
                                                                } else {
                                                                return null;
                                                                }
                                                            })
                                                            }
                                                            {(isMobileApp || viewContentInfo) &&
                                                            <Col span={24} className='mB-2' >
                                                            <div style={{ display: 'flex', justifyContent: 'center', width: '100%' }}>
                                                                { renderButton() }
                                                            </div>
                                                            </Col>}
                                                        </>
                                                    }
                                                    {
                                                        !below768 && isFavouriteInfo && showFavorite && <Col span={contentInfo.type && renderOverlayText(contentInfo.type) ? 12 : 24} className={`mB-1 ${classes.wrapFavoriteIconLayout3}`}>
                                                        <div className={`${isMegreLayout ? contentInfo.isFavorite ? classes.favoriteIconLayout3 : classes.noFavoriteIconLayout3 : classes.noFavoriteIconLayout3} favoriteIcon`} >
                                                            <div className="wrap-icon" onClick={() => onSelectFavorite(contentInfo.id, contentInfo.isFavorite)}>
                                                            {
                                                                <IconBookMark isFavorite={!isMegreLayout && contentInfo.isFavorite}/>
                                                            }
                                                            </div>
                                                        </div>
                                                        </Col>
                                                    }
                                                    {
                                                        sortFields.map((item, index) => {
                                                        if (!below768 || (index !== 0 && index !== 1)) {
                                                            return renderContentInfo({ ...item, index });
                                                        } else {
                                                            return null;
                                                        }
                                                        })
                                                    }
                                                    {
                                                        (!below768 && (isMobileApp || viewContentInfo) && (longFields.length === 0 && (!style.buttonPosition || style.buttonPosition === POSITION_CONFIG.RIGHT.id))) &&
                                                        <Col span={24} style={{ display: 'flex', justifyContent: 'center', width: '100%' }}>
                                                        { renderButton() }
                                                        </Col>
                                                    }
                                                </div>
                                            </Col>
                                        </Row>
                                    }
                                    {
                                        !isMegreLayout &&
                                        <>
                                        <div className={classes.noImage}>
                                            {
                                            contentInfo.type && <div className={classes.contentOverlay}>
                                                {renderOverlayText(contentInfo.type)}
                                            </div>
                                            }
                                            <img src={contentInfo.beContentsId ? window.BEObj.getContentsURL({ cid: contentInfo.beContentsId, type: 2, staging: !!isBEOStaging, cdn: true }) : require('../../assets/img/no-image.png')} />
                                            {
                                                showSubscriptionStatus && contentInfo.isRegistered
                                                ? <div className={`${classes.registered}`} title={t(contentInfo.isSubscriptionPlan ? 'label.subscribed' : 'label.free')} 
                                                    style={{
                                                        right: (isLoggedIn && showFavorite) ? 40 : 0
                                                    }}
                                                >
                                                    <CheckCircleFilled style={{ color: 'green', fontSize: widthHeightIcon }}/>
                                                </div>
                                                : null
                                            }
                                            {
                                                isLoggedIn && showFavorite &&
                                                <div
                                                    className={`${classes.favoriteIcon} favoriteIcon`}
                                                    onClick={() => onSelectFavorite(contentInfo.id, contentInfo.isFavorite)}
                                                >
                                                    <div className="wrap-icon">
                                                        {
                                                            <IconBookMark isFavorite={contentInfo.isFavorite}/>
                                                        }
                                                    </div>
                                                </div>
                                            }
                                        </div>
                                        <div className={'row'} style={{ flex: '1 0 0px', minWidth: 280 }}>
                                            {
                                            sortFields.map((item, index) => renderContentInfo({ ...item, index }))
                                            }
                                        </div>
                                        </>
                                    }
                                    </div>
                                </Col>
                                <Col span={24} className={'mt-2'} >
                                    <Row>
                                    {
                                        longFields.map((item) => renderContentInfo(item))
                                    }
                                    </Row>
                                </Col>
                                {
                                    (isMobileApp || viewContentInfo) && !isMegreLayout &&
                                    <Col span={24} className={getTextAlign(style.buttonPosition || POSITION_CONFIG.RIGHT.id)}>
                                        <Row style={{ padding: 0, justifyContent: getJustifyContent(style.buttonPosition || POSITION_CONFIG.RIGHT.id) }} >
                                            <Col span={ below768 ? 24 : 12} className={`${classes.wrapFlexCenter}`} style={{ width: below768 ? '100%' : '', justifyContent: getJustifyContent(style.buttonPosition || POSITION_CONFIG.RIGHT.id) }}>
                                                { renderButton() }
                                            </Col>
                                        </Row>
                                    </Col>
                                }
                                {
                                    (isMobileApp || viewContentInfo) && isMegreLayout && (!below768 && (longFields.length > 0 || style.buttonPosition === POSITION_CONFIG.LEFT.id || style.buttonPosition === POSITION_CONFIG.CENTER.id)) &&
                                    <Col span={24} className={getTextAlign(style.buttonPosition || POSITION_CONFIG.RIGHT.id)}>
                                        <Row style={{ padding: 0 , justifyContent: getJustifyContent(style.buttonPosition || POSITION_CONFIG.RIGHT.id)}} >
                                            <Col span={ below768 ? 24 : 12}  className={`${classes.wrapFlexCenter}`} style={{ justifyContent: 'center', width: below768 ? '100%' : '' }}>
                                                { renderButton() }
                                            </Col>
                                        </Row>
                                    </Col>
                                }
                
                                <Col span={24} style={{ margin: '2rem 0' }}>
                                    {
                                        viewSettings.contentSearchResultSettingResponse &&
                                        viewSettings.contentSearchResultSettingResponse.contentLayoutDetail === CONTENT_DETAIL_LAYOUT.SERIES &&
                                        viewSettings.contentSearchResultSettingResponse.paramSeriesContent && nameSeries && nameSeries !== '' &&
                                        <SeriesContent
                                            nameSeries={nameSeries}
                                            showFavorite={showFavorite}
                                            idContentDetail={contentInfo.id ? contentInfo.id : contentInfo.detailId}
                                            onSelectFavorite={onSelectFavorite}
                                        />
                                    }
                                </Col>
                            </Row>
                        }
                    </>
                }
                {/* <SubscriptionModal
                    isOpen={isShowSubscription}
                    toggle={() => setIsShowSubscription(false)}
                /> */}
                <ModalConfirm
                    isOpen={showConfirmViewer}
                    toggle={() => setShowConfirmViewer(false)}
                    message={t('label.confirmViewNewTab')}
                    doConfirm={() => openViewOnline({ id: contentDetailId || contentId }, contentGroupId)}
                    doCancel={() => setShowConfirmViewer(false)}
                    backdrop={'static'}
                    level={'info'}
                />
                <LoginModal
                    isOpen={showLoginFormModal}
                    toggle={() => cancelLoginModal()}
                    size="middle"
                    // backdrop={'static'}
                    className="mx-4 my-4"
                >
                    <div className="mx-4 my-4 pl-5 pr-5">
                        <LoginForm/>
                    </div>
                </LoginModal>
                {/* <LoginModal
                    isOpen={showLoginFormModal}
                    toggle={() => cancelLoginModal()}
                    size="md"
                    backdrop={'static'}
                >
                    <LoginEndUserForm
                        onCancel={() => cancelLoginModal()}
                        onSubmit={handleLoginFormSubmit}
                        isShowViewBook={isShowViewBook}
                    />
                </LoginModal> */}
            </div>
        );
    }
};


export default ContentDetailsRender;
