"use client"
import React, { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { makeStyles } from 'tss-react/mui';
import { BUTTON_ACTION, CONTENT_GROUP_TYPE, DISPLAY_SEARCH_RESULTS, LAYOUT_SETTING, PAGINATION, PAGING_TYPE, SEARCH_FIELD } from '@/lib/appConstant';
import { getLayoutViewPage, getSearchSetting } from '@/lib/redux/features/serviceAdmin';
import useResponsive from '@/hooks/useResponsive';
import { useMounted } from '@/hooks/useMounted';
import { useTranslations } from 'use-intl';
import { Col, Row, Skeleton } from 'antd';
import { Chip, TextField } from '@mui/material';
import CheckCircleFilled from '@ant-design/icons/CheckCircleFilled';
import CloseCircleFilled from '@ant-design/icons/CloseCircleFilled';
import AppButton from '../ui/button/app-button';
import { ButtonResponse } from '@/types/serviceAdmin';
import * as _ from 'lodash';
import { getIsDataLoad, getIsSearch } from '@/lib/redux/features/search-page';
import { useRouter } from 'next/navigation';
import IconButtonSearch from '../ui/icon/icon-button-search';

const heightSkeleton = ['210px', '180px', '220px', '230px', '200px', '190px', '160px', '195px', '180px', '210px'];
const offsetLazyload = 250;
if (window?.BEObj) {
    window.BEObj.hosts_staging = 'tial.keyring.net';
}

type MakeStylesType = {
    style: any;
    below768: boolean;
    below393: boolean;
    isListView: boolean;
    isMegreLayout: boolean;
    styleButtonViewBook: any;
    styleButtonViewDetail: any;
};
const useStyle = makeStyles<MakeStylesType>()((
    theme,
    { below768, below393, isListView, style, isMegreLayout, styleButtonViewBook, styleButtonViewDetail }
) => (
    {
      contents: {
        flex: '1 0 0px',
        display: 'flex',
        flexDirection: 'column',
        position: 'relative',
        maxWidth: 'calc(100%)',
        justifyContent: 'center',
        '& .react-multiple-carousel__arrow': {
          display: 'none'
        }
      },
      contentWrap: {
        padding: '0.5rem',
        flex: '1 0 0px',
        minWidth: 155,
        maxWidth: 155,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'center',
        cursor: 'pointer',
        position: 'relative'
      },
      favoriteIconTitleView: {
        position: 'absolute',
        top: 0,
        right: 0,
        // color: '#F08828',
        fontSize: '1rem',
        borderRadius: '50%',
        justifyContent: 'flex-end',
        padding: below768 ? '4px' : '8px',
        margin: '0!important',
        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: '28px',
          height: '28px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }
      },
      favoriteIconTitleView3: {
        position: 'absolute',
        top: 0,
        right: 0,
        // color: '#F08828',
        fontSize: '1rem',
        borderRadius: '50%',
        justifyContent: 'flex-end',
        padding: below768 ? '4px' : '8px',
        margin: '0!important',
        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: '28px',
          height: '28px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }
      },
      likeIcon: {
        width: '30%',
        height: '20%',
        position: 'absolute',
        top: 30,
        right: 0,
        color: '#40A2E3',
        fontSize: '1rem',
        borderRadius: '50%',
        justifyContent: 'flex-end',
        padding: below768 ? '4px' : '8px',
        margin: '0!important',
        display: 'flex',
        cursor: 'pointer',
        zIndex: 1,
        transition: 'all 0.3s ease-in-out',
        '&:hover': {
          transform: 'scale(1.2)'
        },
        '& .wrap-icon': {
          background: '#fff',
          borderRadius: '50%',
          width: '22px',
          height: '22px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }
      },
      favoriteIcon: {
        position: 'absolute',
        bottom: 90,
        right: 10,
        // color: '#F08828',
        fontSize: '1rem',
        borderRadius: '50%',
        justifyContent: 'flex-end',
        padding: below768 ? '4px' : '8px',
        margin: '0!important',
        display: 'flex',
        cursor: 'pointer',
        zIndex: 2,
        transition: 'all 0.3s ease-in-out',
        border: '1.5px solid #999999',
        background: '#fff',
        '&:hover': {
          transform: 'scale(1.2)'
        },
        '& .wrap-icon': {
          background: '#fff',
          borderRadius: '50%',
          width: '24px',
          height: '24px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }
      },
      favoriteIcon3: {
        position: 'absolute',
        bottom: 90,
        right: 10,
        // color: '#F08828',
        fontSize: '1rem',
        borderRadius: '50%',
        justifyContent: 'flex-end',
        padding: below768 ? '4px' : '8px',
        margin: '0!important',
        display: 'flex',
        cursor: 'pointer',
        zIndex: 2,
        transition: 'all 0.3s ease-in-out',
        border: '1.5px solid #999999',
        background: '#00B27B',
        '&:hover': {
          transform: 'scale(1.2)'
        },
        '& .wrap-icon': {
          background: '#00B27B',
          borderRadius: '50%',
          width: '24px',
          height: '24px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }
      },
      contentTitleViewWrapScale: {
        padding: below768 ? '0.25rem' : '0.5rem',
        flex: '1 0 20%',
        maxWidth: '20%',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        cursor: 'pointer',
        position: 'relative',
        ['@media (max-width:1120px)']: { // eslint-disable-line no-useless-computed-key
          flex: '1 0 25%',
          maxWidth: '25%'
        },
        ['@media (max-width:900px)']: { // eslint-disable-line no-useless-computed-key
          flex: '1 0 33.33%',
          maxWidth: below768 ? '49.33%' : '33.33%'
        },
        '& .favoriteIcon': {
          margin: '0.5rem 0.5rem'
        }
      },
      contentWrapScale: {
        borderTop: '1px solid #d2d2d2',
        padding: below768 ? '1.75rem 0.25rem 1.75rem 0' : '2rem 0.5rem 2.25rem 0',
        flex: '1 0 46%',
        maxWidth: '46%',
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'flex-start',
        cursor: 'pointer',
        position: 'relative',
        // margin: '0 2%',
        // ['@media (max-width:1120px)']: { // eslint-disable-line no-useless-computed-key
        //   flex: '1 0 25%',
        //   maxWidth: '25%'
        // },
        ['@media (max-width:900px)']: { // eslint-disable-line no-useless-computed-key
          flex: '1 0 100%',
          maxWidth: '100%'
        },
        '& .favoriteIcon': {
          margin: '0.5rem 0.5rem'
        }
      },
      infoContent: {
        padding: '0 1.5rem',
        maxWidth: '50%'
      },
      favoriteWrap: {
        padding: '0 1.5rem',
        maxWidth: '20%'
      },
      contentImage: {
        textAlign: 'center',
        position: 'relative',
        overflow: 'hidden',
        border: '1px solid #d0d0d0',
        height: below768 ? '160px' : '200px',
        width: below768 ? '120px' : '150px',
        maxWidth: '100%',
        borderRadius: '9px'
      },
      contentTitle: {
        fontWeight: 700,
        textAlign: 'center',
        wordBreak: 'break-word',
        wordWrap: 'break-word',
        color: style.color || '#585757',
        fontSize: '13px',
        width: '100%'
      },
      contentParam: {
        fontWeight: 400,
        color: style.color || '#999999',
        textAlign: 'center',
        wordBreak: 'break-word',
        wordWrap: 'break-word',
        fontSize: '11px',
        width: '100%'
      },
      registeredSubscription: {
        textAlign: 'center',
        wordBreak: 'break-word',
        wordWrap: 'break-word',
        width: '100%'
      },
      noImageHomeAndSearchLayout: {
        objectFit: 'contain',
        height: '100%',
        width: '100%'
      },
      bold: {
        fontWeight: 700
      },
      wrapSkeleton: {
        display: 'flex',
        justifyContent: isListView ? 'flex-start' : 'center',
        marginBottom: '30px',
        flexDirection: 'row',
        padding: isListView ? 0 : '0.5rem',
        flex: '1 0 100%',
        overflow: 'hidden',
        alignItems: 'flex-end',
        '& span': {
          padding: '0 0.5rem'
        },
        '& .skeleton-input-component': {
          // minHeight: below768 ? '166px' : '240px',
          // maxHeight: below768 ? '166px' : '240px',
          maxWidth: below768 ? '118px' : '164px',
          minWidth: below768 ? '118px' : '164px'
        }
      },
      iconPaging: {
        height: below768 ? '100%' : 'unset',
        opacity: below768 ? 0 : 1,
        borderRadius: below768 ? 'none' : '50%',
        fontSize: '1.5rem',
        padding: '0.5rem 1.16rem',
        background: '#20e079a8',
        color: '#fff',
        position: 'absolute',
        zIndex: 10,
        cursor: 'pointer',
        '&:hover': {
          background: '#3ee88d'
        }
      },
      iconPrevPage: {
        marginLeft: below768 ? 0 : 10
      },
      iconNextPage: {
        right: below768 ? 0 : 10
      },
      disabled: {
        background: '#828282!important',
        opacity: 0.8,
        display: 'none'
      },
      allContents: {
        display: 'flex',
        flexFlow: 'row wrap',
        // border: below768 ? 'none' : '1px solid #d0d0d0',
        marginBottom: '0.5rem',
        marginTop: '1rem'
      },
      selectNumItem: {
        width: 72,
        marginLeft: '0.5rem'
      },
      noData: {
        textAlign: 'center',
        padding: '1rem',
        flex: '1 0 100%'
      },
      flexWrap: {
        flexWrap: 'wrap',
        overflowX: 'unset',
        justifyContent: 'start'
      },
      contentOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        padding: '4px'
      },
      chip: {
        background: '#fff',
        backgroundColor: 'white',
        height: '22px',
        color: '#00b27b',
        fontSize: '10px',
        fontWeight: 'bold',
        '& .MuiChip-label': {
          fontSize: '10.17px',
          fontWeight: 700,
          padding: '0 6px'
        }
      },
      chip3: {
        background: '#fff',
        backgroundColor: 'white',
        height: '22px',
        color: '#00b27b',
        fontSize: '10px',
        fontWeight: 'bold',
        '& .MuiChip-label': {
          fontSize: '10.17px',
          fontWeight: 700,
          padding: '0 6px',
          fontFamily: 'Noto Sans JP'
        }
      },
      flexWrapCenter: {
        fontSize: '13px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      },
      contentsHeader: {
        width: '100%',
        position: 'relative',
        minHeight: '150px'
      },
      flexBox: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: isMegreLayout && isListView ? 'space-between' : 'flex-start',
        marginTop: '1rem'
      },

      itemSearchWrap: {
        padding: '0.5rem',
        marginBottom: '0.5rem',
        // flex: '0 0 100%',
        // maxWidth: '100%'
      },
      itemSearch: {
        display: 'flex',
        flexFlow: 'row wrap',
        border: style.borderColor ? `1px solid ${style.borderColor}` : '2px solid #d0d0d0',
        padding: '1rem',
        height: '100%',
        background: style.backgroundColor || '#fff',
        color: style.color || '',
        fontSize: style.fontSize || '1rem',
        justifyContent: 'center'
      },
      itemImage: {
        order: 1
      },
      itemContent: {
        flex: '4 0 0px',
        order: 2,
        padding: '0 1rem',
        minWidth: 250
      },
      itemControl: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        maxWidth: !below768 && !isListView ? '50%' : '100%',
        order: 3
      },
      itemSearchWrapSmall: {
        flex: '0 0 20%',
        flexFlow: 'column wrap'
      },
      itemSearchSmall: {
        flexFlow: 'column'
      },
      itemImageSmall: {
        marginRight: 0,
        marginBottom: '0.5rem',
        textAlign: 'center'
      },
      itemImageSmallListView: {
        marginRight: 0,
        // marginBottom: '0.5rem',
        textAlign: 'center'
      },
      itemContentSmall: {
        flex: '1 0 0px',
        padding: 0,
        minWidth: 'unset'
      },
      itemControlSmall: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'flex-end',
        marginTop: '0.5rem',
        padding: 0
      },
      itemButton: {
        whiteSpace: 'nowrap',
        color: '#ffffff',
        maxHeight: 38
      },
      noImage: {
        maxWidth: 130,
        height: 180,
        width: '100%'
      },
      buttonView: {
        color: '#ffffff',
        fontWeight: 700,
        '&:hover': {
          color: '#ffffff'
        }
      },
      iconButton: {
        marginRight: '0.5rem'
      },
      skeletonItemButton: {
        width: '100%',
        height: '45px'
      },
      skeletonItemImage: {
        width: isListView ? 130 : '100%',
        height: '200px',
        marginBottom: '0.5rem'
      },
      btnViewBook: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        minWidth: '50px',
        maxWidth: '100%',
        width: styleButtonViewBook.width ? styleButtonViewBook.width : 'auto',
        fontSize: below768 ? '12px' : '16px',
        border: '2px solid',
        boxShadow: 'none!important',
        backgroundColor: styleButtonViewBook ? styleButtonViewBook.backgroundColor : '#e26042',
        color: styleButtonViewBook ? styleButtonViewBook.color : '#fff',
        borderColor: styleButtonViewBook ? styleButtonViewBook.borderColor : styleButtonViewBook ? styleButtonViewBook.backgroundColor : '#e26042',
        height: styleButtonViewBook ? styleButtonViewBook.height : 'auto',
        paddingTop: styleButtonViewBook ? (styleButtonViewBook.height ? 0 : 6) : 6,
        paddingBottom: styleButtonViewBook ? (styleButtonViewBook.height ? 0 : 6) : 6,
        '&:hover, &:focus, &:active': {
          backgroundColor: `${styleButtonViewBook ? (styleButtonViewBook.hoverBackgroundColor ? styleButtonViewBook.hoverBackgroundColor : styleButtonViewBook.backgroundColor) : '#e26042a8'}!important`,
          color: `${styleButtonViewBook ? (styleButtonViewBook.hoverColor ? styleButtonViewBook.color : styleButtonViewBook.color) : '#fff'}!important`,
          borderColor: `${styleButtonViewBook ? (styleButtonViewBook.hoverBorderColor ? styleButtonViewBook.hoverBorderColor
            : styleButtonViewBook.hoverBackgroundColor ? styleButtonViewBook.hoverBackgroundColor
              : styleButtonViewBook.borderColor ? styleButtonViewBook.borderColor
                : styleButtonViewBook.backgroundColor ? styleButtonViewBook.backgroundColor
                  : '#e26042a8')
            : '#e26042a8'}!important`
        }
      },
      btnViewDetail: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        maxWidth: '100%',
        minWidth: '50px',
        width: styleButtonViewDetail.width ? styleButtonViewDetail.width : 'auto',
        fontSize: below768 ? '12px' : '16px',
        border: '2px solid',
        boxShadow: 'none!important',
        backgroundColor: styleButtonViewDetail ? styleButtonViewDetail.backgroundColor : '#fff' + ' !important',
        color: styleButtonViewDetail ? styleButtonViewDetail.color : '#3d993a',
        borderColor: styleButtonViewDetail ? (styleButtonViewDetail.borderColor ? styleButtonViewDetail.borderColor : styleButtonViewDetail.backgroundColor) : '#3d993a' + ' !important',
        height: styleButtonViewDetail ? styleButtonViewDetail.height : 'auto',
        paddingTop: styleButtonViewDetail ? (styleButtonViewDetail.height ? 0 : 6) : 6,
        paddingBottom: styleButtonViewDetail ? (styleButtonViewDetail.height ? 0 : 6) : 6,
        '&:hover, &:focus, &:active': {
          backgroundColor: `${styleButtonViewDetail ? (styleButtonViewDetail.hoverBackgroundColor ? styleButtonViewDetail.hoverBackgroundColor : styleButtonViewDetail.backgroundColor) : '#ddeddc'}!important`,
          color: `${styleButtonViewDetail ? (styleButtonViewDetail.hoverColor ? styleButtonViewDetail.color : styleButtonViewDetail.color) : '#3d993a'}!important`,
          borderColor: `${styleButtonViewDetail ? (styleButtonViewDetail.hoverBorderColor ? styleButtonViewDetail.hoverBorderColor
            : styleButtonViewDetail.hoverBackgroundColor ? styleButtonViewDetail.hoverBackgroundColor
              : styleButtonViewDetail.borderColor ? styleButtonViewDetail.borderColor
                : styleButtonViewDetail.backgroundColor ? styleButtonViewDetail.backgroundColor
                  : '#3d993a')
            : '#3d993a'}!important`
        }
      },
      field0: {
        fontSize: 18,
        fontWeight: 700,
        color: style.color || '#585757'
      },
      field1: {
        fontSize: 13,
        fontWeight: 400,
        color: style.color || '#585757'
      },
      field2: {
        fontSize: 13,
        fontWeight: 400,
        color: style.color || '#999999'
      },
      subscriptionStatus: {
        fontWeight: 700,
        fontSize: isListView ? below393 ? '8px' : '13px' : '11px',
        display: 'flex',
        alignItems: 'center'
      },
      contentTitleView: {
        display: 'flex',
        justifyContent: 'center',
        flexDirection: 'column',
        alignItems: 'center',
        width: '100%',
        border: style.borderColor ? `1px solid ${style.borderColor}` : '',
        background: style.backgroundColor || '',
        color: style.color || ''
      },
      contentListView: {
        display: 'flex',
        alignItems: 'flex-start',
        width: '100%',
        border: style.borderColor ? `1px solid ${style.borderColor}` : '',
        background: style.backgroundColor || '',
        color: style.color || ''
      }
    }
));
export const SearchResult = props => {
  const {
    data,
    showContentDetail,
    isLoggedIn,
    onSelectFavorite,
    isListView,
    openViewOnline,
    renderContentInfo,
    contentSetting,
    displaySetting,
    pagingType,
    pagination,
    onChangePage
  } = props;

  const t = useTranslations("");
  const dispatch = useAppDispatch();
  const router = useRouter();
  const mounted = useMounted();
  const { below768, getBelow768 } = useResponsive();
  const below393 = getBelow768(393);
  
  const layoutViewPage = useAppSelector(getLayoutViewPage);
  const isLoaded = useAppSelector(getIsDataLoad);
  const isSearch = useAppSelector(getIsSearch);

  const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
  const isScrollPage = pagingType === PAGING_TYPE.SCROLL && layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;

  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 initialButton = {
    backgroundColor: '',
    color: '',
    height: 0,
    borderColor: '',
    hoverBackgroundColor: '',
    hoverColor: '',
    hoverBorderColor: '',

  };
  const style = useAppSelector(getSearchSetting);
  const styleButtonViewBook = style.buttons && style.buttons.length > 0 ? style.buttons.filter(item => item.actionType === BUTTON_ACTION.VIEW_BOOK.id)[0] : { ...initialButton } as ButtonResponse;
  const styleButtonViewDetail = style.buttons && style.buttons.length > 0 ? style.buttons.filter(item => item.actionType === BUTTON_ACTION.VIEW_DETAIL.id)[0] : {} as ButtonResponse;

  const listener = () => {
    const element = document.getElementById('endSearchResultPage');
    if (element && element.getBoundingClientRect()) {
      const check = element.getBoundingClientRect().bottom <= window.innerHeight + offsetLazyload;
      if (check && pagination && pagination.totalPages > pagination.page) {
        onChangePage && onChangePage(pagination.page + 1);
      }
    }
  };

  const debounceListener = _.debounce(listener, 500);


  const { classes } = useStyle({ below768, below393, isListView, style, isMegreLayout, styleButtonViewBook, styleButtonViewDetail });
  useEffect(() => {
    if (isScrollPage && pagination && pagination.totalPages > pagination.page && layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id) {
      setTimeout(() => {
        listener();
      }, 100);
      window.addEventListener('scroll', debounceListener, true);
      return () => {
        window.removeEventListener('scroll', debounceListener, true);
      };
    }
  }, [pagingType, pagination, layoutViewPage]);

  const renderFavoriteButton = (content) => {
    if (isLoggedIn) {
      return (
        <div
          className={`${!isListView
            ? isMegreLayout
              ? content.isFavorite
                ? classes.favoriteIconTitleView3
                : classes.favoriteIconTitleView
              : classes.favoriteIconTitleView
            : isMegreLayout
              ? content.isFavorite
                ? classes.favoriteIcon3
                : classes.favoriteIcon
              : classes.favoriteIcon} favoriteIcon`}
          style={{
            color: isMegreLayout ? content.isFavorite ? '#fff' : '#585757' : '#F08828'
          }}
          onClick={() => {
            const contentGroupId = content.contentGroupId ? content.contentGroupId : content.contentGroupResponse.id;
            onSelectFavorite(content.id, content.isFavorite, contentGroupId);
          }}
        >
          <div className="wrap-icon">
            {
              isMegreLayout
                ? content.isFavorite
                  ? (<i className={'far fa-bookmark'}></i>)
                  : (<i className={'far fa-bookmark'}></i>)
                : content.isFavorite
                  ? (<i className={'fas fa-bookmark'}></i>)
                  : (<i className="far fa-bookmark"></i>)
            }
          </div>
        </div>
      );
    }
  };

  const renderSkeleton = () => {
    if (isMegreLayout) {
      return <React.Fragment>
        {
          [...Array(PAGINATION.size).keys()].map((skeleton, index) => (
            <div key={`skeleton-component-${skeleton}`} className={`${!isListView ? classes.contentTitleViewWrapScale : classes.contentWrapScale} ${classes.wrapSkeleton}`}>
              <Skeleton style={{ height: heightSkeleton[index % 10] }} className={'skeleton-input-component'} />
            </div>
          ))
        }
      </React.Fragment>;
    } else {
      return (
        <React.Fragment>
          {
            [...Array(PAGINATION.size).keys()].map(item => {
              return (
                <div key={`content-${item}`} className={`${classes.itemSearchWrap} ${!isListView ? 'item-search-wrap' : ''}`}>
                  <div className={`${classes.itemSearch} ${!isListView ? classes.itemSearchSmall : ''}`}>
                    <div className={`${classes.itemImage} ${!isListView ? classes.itemImageSmall : ''}`}>
                      <div className={`${classes.noImage} ${classes.skeletonItemImage}`}>
                        <Skeleton style={{ height: '100%' }} />
                      </div>
                    </div>
                    <div className={`${classes.itemContent} ${classes.skeletonItemImage} ${!isListView ? classes.itemContentSmall : ''}`}>
                      <Row>
                        <Col sm={24} className={'mB-1'}>
                          <span>
                            <Skeleton />
                          </span>
                        </Col>
                        <Col sm={24} className={'mB-1'}>
                          <span>
                            <Skeleton />
                          </span>
                        </Col>
                        <Col sm={24} className={'mB-1'}>
                          <span>
                            <Skeleton />
                          </span>
                        </Col>
                      </Row>
                    </div>
                  </div>
                </div>
              );
            })
          }
        </React.Fragment>
      );
    }
  };

  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 (!isListView) {
      return (<Chip style={{ fontSize: 20 }} className={`${isMegreLayout ? classes.chip3 : classes.chip}`} label={label} />);
    }
    return <span style={{ color: '#00B27B', fontWeight: 700 }}>{label}</span>;
  };

  const getOneParam = (itemSetting, contentInfo) => {
    switch (itemSetting.field) {
      case SEARCH_FIELD.TITLE.id:
        return contentInfo[SEARCH_FIELD.TITLE.dbKey];
      case SEARCH_FIELD.AUTHOR.id:
        return contentInfo[SEARCH_FIELD.AUTHOR.dbKey];
      case SEARCH_FIELD.KEYWORDS.id:
        return contentInfo[SEARCH_FIELD.KEYWORDS.dbKey];
      case SEARCH_FIELD.TOC.id:
        return contentInfo[SEARCH_FIELD.TOC.dbKey];
      case SEARCH_FIELD.DISTRIBUTOR.id:
        return contentInfo[SEARCH_FIELD.DISTRIBUTOR.dbKey];
      case SEARCH_FIELD.DESCRIPTION.id:
        return contentInfo[SEARCH_FIELD.DESCRIPTION.dbKey];
      case SEARCH_FIELD.PARAM_1.id:
        return contentInfo[SEARCH_FIELD.PARAM_1.dbKey];
      case SEARCH_FIELD.PARAM_2.id:
        return contentInfo[SEARCH_FIELD.PARAM_2.dbKey];
      case SEARCH_FIELD.PARAM_3.id:
        return contentInfo[SEARCH_FIELD.PARAM_3.dbKey];
      case SEARCH_FIELD.PARAM_4.id:
        return contentInfo[SEARCH_FIELD.PARAM_4.dbKey];
      case SEARCH_FIELD.PARAM_5.id:
        return contentInfo[SEARCH_FIELD.PARAM_5.dbKey];
      default:
        return '';
    }
  };

  const renderContentInfoListView = (itemSetting, contentInfo, isFullWidth, index) => {
    let searchField;
    let className: string | null = null;
    switch (itemSetting.field) {
      case SEARCH_FIELD.TITLE.id:
        searchField = SEARCH_FIELD.TITLE;
        break;
      case SEARCH_FIELD.AUTHOR.id:
        searchField = SEARCH_FIELD.AUTHOR;
        break;
      case SEARCH_FIELD.KEYWORDS.id:
        searchField = SEARCH_FIELD.KEYWORDS;
        break;
      case SEARCH_FIELD.TOC.id:
        searchField = SEARCH_FIELD.TOC;
        break;
      case SEARCH_FIELD.DISTRIBUTOR.id:
        searchField = SEARCH_FIELD.DISTRIBUTOR;
        break;
      case SEARCH_FIELD.DESCRIPTION.id:
        searchField = SEARCH_FIELD.DESCRIPTION;
        break;
      case SEARCH_FIELD.PARAM_1.id:
        searchField = SEARCH_FIELD.PARAM_1;
        break;
      case SEARCH_FIELD.PARAM_2.id:
        searchField = SEARCH_FIELD.PARAM_2;
        break;
      case SEARCH_FIELD.PARAM_3.id:
        searchField = SEARCH_FIELD.PARAM_3;
        break;
      case SEARCH_FIELD.PARAM_4.id:
        searchField = SEARCH_FIELD.PARAM_4;
        break;
      case SEARCH_FIELD.PARAM_5.id:
        searchField = SEARCH_FIELD.PARAM_5;
        break;
      default: break;
    }
    switch (index) {
      case 0:
        className = classes.field0;
        break;
      case 1:
        className = classes.field1;
        break;
      case 2:
        className = classes.field2;
        break;
      default:
        break;
    }
    return (
      <Col
        sm={isFullWidth ? 12 : Number(itemSetting.size) * 2}
        key={`key-detail-${searchField.dbKey}-${(new Date()).getTime()}`}
        id={`key-detail-${searchField.dbKey}-${(new Date()).getTime()}`}
        className={`${itemSetting.hasBox && 'has-box'} ${className}`}
      >
        {
          itemSetting.isShowLabel && isMegreLayout &&
          <span >
            {`${itemSetting.title}: `}
          </span>
        }
        {
          itemSetting.hasBox
            ? <TextField variant={'outlined'} multiline type={'textarea'} value={contentInfo[searchField.dbKey]} />
            : <span dangerouslySetInnerHTML={{ __html: contentInfo[searchField.dbKey] }} />
        }
      </Col>
    );
  };

  const renderContentTitleView = (item, index) => {
    const contentGroupId = item.contentGroupId ? item.contentGroupId : item.contentGroupResponse.id;
    var registeredSubscription: any = null;
    if (item.isFree || item.isRegistered) {
      registeredSubscription = (<span className={`${classes.flexWrapCenter} ${classes.subscriptionStatus}`} style={{ color: '#00B27B' }}>
        <CheckCircleFilled style={{ fontSize: 'small', margin: '2px 1px 0 0' }} /> {t('label.' + (item.isFree ? 'free' : 'subscribed'))}
      </span>);
    } else {
      registeredSubscription = (<span className={`${classes.flexWrapCenter} ${classes.subscriptionStatus}`} style={{ color: '#E44A4A' }}>
        <CloseCircleFilled style={{ fontSize: 'small', margin: '2px 1px 0 0' }} /> {t('label.subscriptionRegister')}
      </span>);
    }
    return (
      <div
        key={`content-${index}-${item.id}`}
        className={classes.contentTitleViewWrapScale}
        style={{ marginBottom: '30px' }}
      >
        <div className={classes.contentTitleView} >
          <div
            className={`${classes.contentImage}`}
          >
            {
              item.type && <div className={classes.contentOverlay}>
                {renderOverlayText(item.type)}
              </div>
            }
            {renderFavoriteButton(item)}
            {/* {
              showTrending && renderLikeButton(item)
            } */}
            <div style={{ width: '100%', height: '100%' }} onClick={() => showContentDetail({ contentId: item.id, contentGroupId: contentGroupId })}>
              <img
                className={classes.noImageHomeAndSearchLayout}
                src={item.beContentsId && window?.BEObj ? window.BEObj.getContentsURL({ cid: item.beContentsId, type: 2, staging: isBEOStaging, cdn: true }) : '/assets/img/no-image.png'}
              />
            </div>
          </div>
          {/* <div className={`${classes.contentTitle}`} onClick={() => showContentDetail({ contentId: item.id, contentGroupId: contentGroupId })}>
            <span dangerouslySetInnerHTML={{ __html: item.title }} />
          </div> */}
          {
            contentSetting && contentSetting[0] && getOneParam(contentSetting[0], item) &&
            getOneParam(contentSetting[0], item).trim() !== '' &&
            <div className={`${classes.contentTitle}`} onClick={() => showContentDetail({ contentId: item.id, contentGroupId: item.content_group_id ? item.content_group_id : contentGroupId })}>
              <span dangerouslySetInnerHTML={{ __html: getOneParam(contentSetting[0], item) }} />
            </div>
          }
          {
            contentSetting && contentSetting[1] && getOneParam(contentSetting[1], item) &&
            getOneParam(contentSetting[1], item).trim() !== '' &&
            <div className={`${classes.contentParam}`} onClick={() => showContentDetail({ contentId: item.id, contentGroupId: contentGroupId })}>
              <span dangerouslySetInnerHTML={{ __html: getOneParam(contentSetting[1], item) }} />
            </div>
          }
          <div className={`${classes.registeredSubscription}`}>
            {registeredSubscription}
          </div>
        </div>
      </div>
    );
  };

  const renderContentListView = (item: any, index: number) => {
    const contentGroupId = item.contentGroupId ? item.contentGroupId : item.contentGroupResponse.id;
    var registeredSubscription: any = null;
    if (item.isFree || item.isRegistered) {
      registeredSubscription = (<span className={classes.subscriptionStatus} style={{ color: '#00B27B' }}>
        <CheckCircleFilled style={{ fontSize: 'small', margin: '2px 1px 0 0' }} /> {t('label.' + (item.isFree ? 'free' : 'subscribed'))}
      </span>);
    } else {
      registeredSubscription = (<span className={classes.subscriptionStatus} style={{ color: '#E44A4A' }}>
        <CloseCircleFilled style={{ fontSize: 'small', margin: '2px 1px 0 0' }} /> {t('label.subscriptionRegister')}
      </span>);
    }
    return (
      <div
        key={`content-${index}-${item.id}`}
        className={classes.contentWrapScale}
      >
        <div className={classes.contentListView}>
          <div
            className={`${classes.contentImage}`}
            style={{ maxWidth: '40%' }}
          >
            {/* {
              showTrending && renderLikeButton(item)
            } */}
            <div style={{ width: '100%', height: '100%' }} onClick={() => showContentDetail({ contentId: item.id, contentGroupId: contentGroupId })}>
              <img
                className={classes.noImageHomeAndSearchLayout}
                src={item.beContentsId && window?.BEObj ? window.BEObj.getContentsURL({ cid: item.beContentsId, type: 2, staging: isBEOStaging, cdn: true }) : '/assets/img/no-image.png'}
              />
            </div>
          </div>
          <div className={`${classes.infoContent}`}>
            {
              item.type && <div style={{ color: '#00B27B' }} onClick={() => showContentDetail({ contentId: item.id, contentGroupId: contentGroupId })}>
                {renderOverlayText(item.type)}
              </div>
            }
            {/* <div className={`${classes.contentTitle}`} style={{ textAlign: 'left', marginBottom: 16 }} onClick={() => showContentDetail({ contentId: item.id, contentGroupId: contentGroupId })}>
              <span dangerouslySetInnerHTML={{ __html: item.title }} />
            </div> */}
            <Row>
              {
                contentSetting && contentSetting.map((setting, index) => {
                  if (index >= 3) {
                    return null;
                  }
                  const renderFields = renderContentInfoListView(setting, item, displaySetting === DISPLAY_SEARCH_RESULTS.TITLE_VIEW, index);
                  return renderFields;
                })
              }
            </Row>
            <div className={`${classes.registeredSubscription}`} style={{ textAlign: 'left' }}>
              {registeredSubscription}
            </div>
          </div>
          <div className={`${classes.favoriteWrap}`}>
            {renderFavoriteButton(item)}
          </div>
        </div>
      </div>
    );
  };

  const renderContentHomeAndSearchLayout = () => {
    // if (isLoaded && !isScrollPage) {
    //   return renderSkeleton();
    // }

    if (data && data.length > 0) {
      return data.map((item, index) => {
        return !isListView ? renderContentTitleView(item, index) : renderContentListView(item, index);
      });
    } else if (!isLoaded) {
      return (
        <div className={classes.noData}>
            {t('text.noData')}
        </div>
      );
    }
  };

  const renderButtonDisplayBook = (item) => {
    var valueIcon = 'fas fa-book-open';
    if (styleButtonViewBook.isShowIcon && styleButtonViewBook.icon && styleButtonViewBook.icon !== '') {
      valueIcon = styleButtonViewBook.icon;
    }
    return (
      <AppButton
        customColor={true}
        className={`${classes.itemButton} ${classes.bold} ${classes.btnViewBook}`}
        onClick={() => openViewOnline(item)}
      >
        {
          styleButtonViewBook && styleButtonViewBook.label !== ''
            ? <React.Fragment>
              {
                isListView
                  ? <span>{styleButtonViewBook.label}</span>
                  : <span>
                      <IconButtonSearch value={valueIcon}/>
                  </span>
              }
            </React.Fragment>
            : <React.Fragment>
              <span className={isListView ? classes.iconButton : ''}>
                <IconButtonSearch value={valueIcon}/>
              </span>
              {isListView ? t('label.displayBook') : null}
            </React.Fragment>
        }
      </AppButton>
    );
  };

    const renderButtonShowDetail = (item) => {
        let valueIcon = 'fas fa-info-circle';
        if (styleButtonViewBook.isShowIcon && styleButtonViewBook.icon && styleButtonViewBook.icon !== '') {
          valueIcon = styleButtonViewBook.icon;
        }
        return (
            <AppButton
              customColor={true}
              className={`${isListView ? 'mB-1' : ''} ${classes.itemButton} ${classes.bold} ${classes.btnViewDetail}`}
              onClick={() => showContentDetail({ contentId: item.id })}
            >
                {
                    styleButtonViewDetail && styleButtonViewDetail.label !== ''
                    ? <React.Fragment>
                        {
                            isListView
                            ? <span>{styleButtonViewDetail.label}</span>
                            : <span>
                              <IconButtonSearch value={valueIcon}/>
                            </span>
                        }
                    </React.Fragment>
                    : <React.Fragment>
                        <span className={isListView ? classes.iconButton : ''}>
                          <IconButtonSearch value={valueIcon}/>
                        </span>
                        {isListView ? t('label.showDetail') : null}
                    </React.Fragment>
                }
            </AppButton>
        );
    };
    
    return (
        <>
            <div className={`search-result `} style={{
                  display: 'flex',
                  flexWrap: 'wrap',
                  justifyContent: isMegreLayout && isListView ? 'space-between' : 'flex-start',
                  marginTop: '1rem'
            }}>
                {
                    isSearch || (isLoaded && !isScrollPage)
                    ? null
                    : (isMegreLayout
                        ? renderContentHomeAndSearchLayout()
                        : data.map((item: any) => {
                            return (
                                <div key={`content-${item.id}`} className={`${classes.itemSearchWrap} ${!isListView ? 'item-search-wrap' : ''}`}>
                                    <div className={`${classes.itemSearch} `} style={!isListView ? {flexFlow: 'column'} : {}}>
                                        <div className={`${classes.itemImage} ${!isListView ? classes.itemImageSmall : ''}`}>
                                            <img className={classes.noImage} src={item.beContentsId && window?.BEObj ? window.BEObj.getContentsURL({ cid: item.beContentsId, type: 2, staging: isBEOStaging, cdn: true }) : '/assets/img/no-image.png'} />
                                        </div>
                                        <div className={`${classes.itemContent}`}
                                          style={ !isListView ? {
                                            flex: '1 0 0px',
                                            padding: 0,
                                            minWidth: 'unset'
                                          } : {}}
                                        >
                                            <Row>
                                                {
                                                    contentSetting && contentSetting.map((setting: any) => {
                                                        const renderFields = renderContentInfo(setting, item, displaySetting === DISPLAY_SEARCH_RESULTS.TITLE_VIEW);
                                                        return renderFields;
                                                    })
                                                }
                                            </Row>
                                        </div>
                                        <div className={`${classes.itemControl} ${!isListView ? classes.itemControlSmall : 'small-screen'}`}>
                                            {renderButtonShowDetail(item)}
                                            {
                                                (item.view === true || item.view === false) && item.view && renderButtonDisplayBook(item)
                                            }
                                        </div>
                                    </div>
                                </div>
                            );
                        })
                    )
                }
                {
                    isLoaded &&
                    renderSkeleton()
                }
            </div>
            {isMegreLayout && <div id='endSearchResultPage'></div>}
        </>
    );
};

export default SearchResult;
