"use client"
import React, { useCallback, useEffect, useState } from 'react';
import * as _ from 'lodash';
import { getLayoutSettingAll, getLayoutViewPage } from '@/lib/redux/features/serviceAdmin';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { getIsClearData, getIsLoadingByGroup, setDataCurrentPage, setDataNextPage, setDataPrePage } from '@/lib/redux/features/content';
import { LayoutSettingResponse } from '@/types/serviceAdmin';
import { useMounted } from '@/hooks/useMounted';
import classNames from 'classnames';
import { makeStyles } from 'tss-react/mui';
import { CASE_CHANGE_PAGE, CONTENT_GROUP_TYPE, LAYOUT_SETTING, LOAD_CONTENT_ACTION_TYPE, mainColorMegreLayout, PAGINATION } from '@/lib/appConstant';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import Button from '@mui/material/Button';

import { useTranslations } from 'next-intl';
import { getIsMobileApp } from '@/lib/redux/features/auth';
import { CheckCircleIcon } from 'lucide-react';
import AppSelect from '../ui/select';
import Skeleton from '@mui/material/Skeleton';
import CustomPagination from '../ui/custom-pagination';
import { FormItem } from '../ui/form';
import CloseCircleFilled from '@ant-design/icons/CloseCircleFilled';
import RightOutlined from '@ant-design/icons/RightOutlined';
import LeftOutlined from '@ant-design/icons/LeftOutlined';
import useResponsive from '@/hooks/useResponsive';
import { Select } from 'antd';
import IconBookMark from '../ui/icon/icon-book-mark';
import { useParams, useSearchParams } from 'next/navigation';

const optionNumItem = [
  { value: 5, label: '5' },
  { value: 10, label: '10' },
  { value: 15, label: '15' },
  { value: 20, label: '20' },
  { value: 25, label: '25' },
  { value: 30, label: '30' }
];

const heightSkeleton = [180, 160, 140, 160, 160, 140, 180, 200, 140, 170];
const heightSkeletonMobile = [160, 140, 120, 140, 140, 120, 160, 180, 120, 150];
const offsetLazyload = 200;


type MakeStylesType = {
  barBackground: any;
  barText: any;
  moreLessBackground: any;
  moreLessTextColor: any;
  isMegreLayout: boolean;
  below768: boolean;
}
const useStyle = makeStyles<MakeStylesType>()((
  theme,
  { barBackground, barText, below768, isMegreLayout, moreLessBackground, moreLessTextColor }
) => ({
  title: {
      padding: '0.5rem 1rem',
      fontWeight: 700,
      background: barBackground || '#808080',
      color: barText || '#fff',
      cursor: 'pointer',
      // borderLeft: '1px solid #d2d2d2',
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      '& .button-more-less': {
          borderRadius: '19px!important',
          backgroundColor: moreLessBackground || '#6c757d',
          borderColor: moreLessBackground || '#6c757d',
          color: moreLessTextColor || '#fff',
          '&:hover': {
              backgroundColor: moreLessBackground || '#6c757d',
              borderColor: moreLessBackground || '#6c757d',
              color: moreLessTextColor || '#fff'
          },
          '&:active': {
              backgroundColor: moreLessBackground || '#6c757d',
              borderColor: moreLessBackground || '#6c757d',
              color: moreLessTextColor || '#fff'
          }
      },
      '& .tag': {
          // borderRadius: '10px',
          padding: '6px',
          fontWeight: 'bold'
          // color: 'white'
      },
      '& .free': {
          color: mainColorMegreLayout
      },
      '& .subscription': {
          color: '#e44a4a'
      },
      '& .subscribed': {
          color: isMegreLayout ? mainColorMegreLayout : '#00fbff'
      }
  },
  contents: {
      flex: '1 0 0px',
      display: 'flex',
      flexDirection: 'column',
      position: 'relative',
      maxWidth: 'calc(100%)',
      justifyContent: 'center',
      '& .react-multiple-carousel__arrow': {
          display: 'none'
      }
  },
  contentsRow: {
      maxWidth: '100%',
      display: 'flex',
      overflowX: 'auto',
      // border: '1px solid #d0d0d0',
      padding: below768 ? '0px' : '0.5rem 1rem',
      justifyContent: 'start'
  },
  contentWrap: {
      padding: below768 ? '0.5rem 0px' : '0.5rem',
      flex: '1 0 0px',
      minWidth: 164,
      maxWidth: 164,
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'flex-start',
      alignItems: 'center',
      cursor: 'pointer',
      position: 'relative'
  },
  contentWrapSkeleton: {
      padding: below768 ? '0.5rem 0px' : '0.5rem',
      flex: '1 0 0px',
      minWidth: 164,
      maxWidth: 164,
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'flex-end',
      alignItems: 'center',
      cursor: 'pointer',
      position: 'relative'
  },
  favoriteIcon: {
      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',
      zIndex: 1,
      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'
      }
  },
  favoriteIcon3: {
      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',
      zIndex: 1,
      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'
      }
  },
  contentWrapScale: {
      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: '33.33%'
      },
      '& .favoriteIcon': {
          margin: '0.5rem 0.5rem'
      }
  },
  contentImage: {
      textAlign: 'center',
      position: 'relative',
      overflow: 'hidden',
      border: '1px solid #d0d0d0',
      height: below768 ? '160px' : '200px',
      width: below768 ? '120px' : '150px',
      maxWidth: '100%',
      borderRadius: '10px'
  },
  contentImageSkeleton: {
      textAlign: 'center',
      position: 'relative',
      overflow: 'hidden',
      width: below768 ? '120px' : '150px',
      maxWidth: '100%'
  },
  contentImageSkeletonIncremental: {
      textAlign: 'center',
      display: 'flex',
      alignItems: 'center',
      position: 'relative',
      overflow: 'hidden',
      width: below768 ? '120px' : '150px',
      maxWidth: '100%'
  },
  contentTitle: {
      textAlign: 'center',
      wordBreak: 'break-word',
      wordWrap: 'break-word',
      width: '100%'
  },
  noImage: {
      objectFit: 'contain',
      height: '100%',
      width: '100%'
  },
  bold: {
      fontWeight: 700
  },
  wrapSkeleton: {
      display: 'flex',
      flexDirection: 'row',
      padding: '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'
      }
  },
  pointer: {
      cursor: 'pointer'
  },
  iconPaging: {
    height: '52px',
    width: '52px',
    cursor: 'pointer',
    opacity: 1,
    borderRadius: '50%',
    fontSize: below768 ? '1.4rem' : '1.5rem',
    padding: below768 ? '0.2rem 0.82rem' : '0.5rem 1.16rem',
    background: '#20e079a8',
    color: '#fff',
    position: 'absolute',
    zIndex: 10,
    '& span': {
      width: '100%',
      textAlign: 'center',
      fontWeight: 'bold'
    },
    '&: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'
  },
  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: mainColorMegreLayout,
      fontSize: '8px',
      fontWeight: 'bold',
      border: '1px solid #d0d0d0',
      '& .MuiChip-label': {
          fontSize: '10px',
          padding: '0 6px'
      }
  },
  chip3: {
      background: '#fff',
      backgroundColor: 'white',
      height: '22px',
      color: mainColorMegreLayout,
      fontSize: '8px',
      fontWeight: 'bold',
      border: '1px solid #d0d0d0',
      '& .MuiChip-label': {
          fontSize: '10px',
          padding: '0 6px',
          fontFamily: 'Noto Sans JP'
      }
  }
}));

const ContentListRender = (props: any) => {
  const {
      handleLoadDetail,
      contentGroup,
      showPagination = false,
      pageSize,
      changePageSize,
      onSelectContentGroup,
      isLoggedIn,
      onSelectFavorite,
      isShowDetail,
      showFavorite,
      showSubscriptionStatus,
      handleLoadContentsNextPrevPage,
      dataNextPage,
      dataPrePage,
      selectHashtags = [],


      // contentGroupId,
      // contentId
  } = props;

  const f = useTranslations("");
  const mounted = useMounted();
  const dispatch = useAppDispatch();
  const paramsPath = useParams();
  const searchParams = useSearchParams();
  const contentGroupId = paramsPath.contentGroupId || searchParams.get('contentGroupId');
  const contentId = searchParams.get('contentId');
  const layoutViewPage = useAppSelector(getLayoutViewPage);
  const layoutSetting: LayoutSettingResponse = useAppSelector(getLayoutSettingAll) || {} as LayoutSettingResponse;
  const isClearData = useAppSelector(getIsClearData);
  const loadingByGroup = useAppSelector(getIsLoadingByGroup);
  const isMobileApp = useAppSelector(getIsMobileApp);
  const { below768 } = useResponsive();

  const isHomeLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT.id;
  const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
  const { barBackground, barText, moreLessBackground, moreLessTextColor } = layoutSetting;

  const [isInfinityLoad, setIsInfinityLoad] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const { contents, totalPages, loadContentActionType, page } = contentGroup;

  const caseChangePage = showPagination ? CASE_CHANGE_PAGE.pagination : ((isInfinityLoad || (loadContentActionType === LOAD_CONTENT_ACTION_TYPE.SCROLL && (isMegreLayout || isHomeLayout))) ? CASE_CHANGE_PAGE.scroll : CASE_CHANGE_PAGE.default);
  const isSelectedHashtag = (selectHashtags && selectHashtags.length > 0);

  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 pathname = window.location.pathname;
  const isSearchContent = pathname.includes('search');

  const { classes } = useStyle({ barBackground, barText, below768, isMegreLayout, moreLessBackground, moreLessTextColor });

  const handleScrollInfinity = (e: any) => {
      if (contentGroup.page + 1 <= contentGroup.totalPages && !loadingByGroup[contentGroup.id]) {
          const element = e.target;
          if (element.scrollLeft + element.clientWidth + offsetLazyload >= element.scrollWidth) {
              // init change page
              onChangePage(contentGroup.page + 1, );
          }
      }
  };

  const renderOverlayText = (contentGroupType: any) => {
      var label = '';
      switch (contentGroupType) {
          case CONTENT_GROUP_TYPE.NEW:
              label = f('label.newOverlay');
              break;
          case CONTENT_GROUP_TYPE.POPULAR:
              label = f('label.popularOverlay');
              break;
          case CONTENT_GROUP_TYPE.RECOMMEND:
              label = f('label.recommendOverlay');
              break;
          default:
              label = '';
      }
      return (<Chip className={`${isMegreLayout ? classes.chip3 : classes.chip}`} label={label} />);
  };

  const renderRowContent = (items: any, index?: number) => {
      if (!mounted) {
          return null;
      }
      return (
          <Box id={`contents-row-${caseChangePage === CASE_CHANGE_PAGE.scroll ? contentGroup.id : `${index}-${items[0].id}`}`} key={`contents-${items[0].id}`} className={`${classes.contentsRow} ${contentGroup.isWrapLine && caseChangePage !== CASE_CHANGE_PAGE.scroll ? classes.flexWrap : ''}`} onScroll={e => caseChangePage === CASE_CHANGE_PAGE.scroll && handleScrollInfinity(e)}>
              {
                  items.map((item: any, index: number) => {
                      return (
                          <div key={`row-content-${index}-${item.id}`} className={classes.contentWrap}>
                              <div className={`${classes.contentImage}`}>
                              { showFavorite && renderFavoriteButton(item) }
                              {
                                  item.type &&
                                  <div className={classes.contentOverlay}>
                                      {renderOverlayText(item.type)}
                                  </div>
                              }
                              <img
                                  className={classes.noImage}
                                  onClick={() => handleLoadDetail(item.id, contentGroup.id)}
                                  src={item.beContentsId && window?.BEObj ? window.BEObj.getContentsURL({ cid: item.beContentsId, type: 2, staging: !!isBEOStaging, cdn: true }) : require('@/assets/img/no-image.png')}
                              />
                              </div>
                              <div className={classes.contentTitle} onClick={() => handleLoadDetail(item.id, contentGroup.id)}>
                              {
                                  isSearchContent || isSelectedHashtag || (item.title.includes('<em>') && item.title.includes('</em>'))
                                  ? (<span dangerouslySetInnerHTML={{ __html: item.title }} />)
                                  : (<span>{item.title}</span>)
                              }
                              </div>
                          </div>
                      );
                  })
              }
              { caseChangePage === CASE_CHANGE_PAGE.scroll && loadingByGroup[contentGroup.id] && renderSkeletIsInfinityLoad(false) }
          </Box>
      );
  };

  const renderContent = (item: any, index?: number) => {
      if (!mounted) {
          return null;   
      }
      return (
          <div key={`content-${index}-${item.id}`} className={classNames({ [classes.contentWrapScale]: true })}>
              <div className={`${classes.contentImage}`}>
                  {
                      item.type &&
                      <div className={classes.contentOverlay}>
                          {renderOverlayText(item.type)}
                      </div>
                  }
                  { showFavorite && renderFavoriteButton(item) }
                  <div onClick={() => handleLoadDetail(item.id, contentGroup.id)} style={{ width: '100%', height: '100%' }}>
                      <img
                          className={classes.noImage}
                          src={item.beContentsId && window?.BEObj ? window.BEObj.getContentsURL({ cid: item.beContentsId, type: 2, staging: !!isBEOStaging, cdn: true }) : require('@/assets/img/no-image.png')}
                      />
                  </div>
              </div>
              <div className={`${classes.contentTitle}`} onClick={() => handleLoadDetail(item.id, contentGroup.id)}>
                  {
                      isSearchContent || isSelectedHashtag
                      ? (<span dangerouslySetInnerHTML={{ __html: item.title }} />)
                      : (<span>{item.title}</span>)
                  }
              </div>
          </div>
      );
  };

  const renderRowContents = () => {
    let numberItemOfRow = 0;
    let rowItems: any[] = [];
    if (caseChangePage !== CASE_CHANGE_PAGE.scroll && (contentGroup.isLoading || !contentGroup.contents)) {
      return renderSkeleton();
    }
    if (caseChangePage === CASE_CHANGE_PAGE.scroll && contentGroup.isLoading && !contentGroup.contents) {
      return renderSkeletIsInfinityLoad(true);
    }
    if (contentGroup.contents && contentGroup.contents.length > 0) {
      if (caseChangePage === CASE_CHANGE_PAGE.scroll) {
        return renderRowContent(contentGroup.contents, contentGroup.contents.length);
      } else {
        return contentGroup.contents.map((item: any, index: number) => {
          rowItems = [...rowItems, item];
          numberItemOfRow++;
          if (numberItemOfRow === contentGroup.itemSize || (index + 1) === contentGroup.contents.length) {
            const cloneRows = [...rowItems];
            numberItemOfRow = 0;
            rowItems = [];
            return renderRowContent(cloneRows, index);
          }
        });
      }
    } else {
      return (
        <div className={classes.noData}>
            {f('text.noData')}
        </div>
      );
    }
  };

  const renderContentsPagination = () => {
    if (contentGroup.isLoading || !contentGroup.contents) {
      return renderSkeleton();
    }

    if (contentGroup.contents && contentGroup.contents.length > 0) {
      const result = contentGroup.contents.map((item, index) => {
        return renderContent(item, index);
      });
      const skeleton = below768 && (contentGroup.isLoading || isLoading) ? renderSkeletIncremental() : null;
      return [...result, skeleton];
    } else {
      return (
        <div className={classes.noData}>
          {f('text.noData')}
        </div>
      );
    }
  };

  const onChangePage = (nextPage: number, nextSize?: number) => {
    if (nextPage < 1 || nextPage > contentGroup.totalPages || nextPage === contentGroup.page) {
      return;
    }
    const params: any = {
      contentGroup: contentGroup,
      caseChangePage: caseChangePage,
      isIncremental: caseChangePage === CASE_CHANGE_PAGE.scroll || (below768 && caseChangePage === CASE_CHANGE_PAGE.pagination)
    };
    if (nextSize) {
      params.size = nextSize;
    }
    if (caseChangePage !== CASE_CHANGE_PAGE.default) {
      params.size = caseChangePage === CASE_CHANGE_PAGE.pagination ? pageSize : PAGINATION.size;
      params.page = nextPage;
      params.isNext = true;
    } else {
      if (nextPage > contentGroup.page) {
        if (!dataNextPage) {
          return;
        }
        dispatch(setDataCurrentPage({ contentGroupId: contentGroup.id, data: dataNextPage, isSelectedHashtag }));
        dispatch(setDataPrePage({ contentGroupId: contentGroup.id, data: contentGroup, isSelectedHashtag }));
        params.isNext = true;
        params.page = nextPage + 1;
        if (params.page > contentGroup.totalPages) {
            dispatch(setDataNextPage({ contentGroupId: contentGroup.id, data: null, isSelectedHashtag }));
        }
      } else {
        if (!dataPrePage) {
          return;
        }
        dispatch(setDataCurrentPage({ contentGroupId: contentGroup.id, data: dataPrePage, isSelectedHashtag }));
        dispatch(setDataNextPage({ contentGroupId: contentGroup.id, data: contentGroup, isSelectedHashtag }));
        params.isNext = false;
        params.page = nextPage - 1;
        if (params.page < 1) {
            dispatch(setDataPrePage({ contentGroupId: contentGroup.id, data: null, isSelectedHashtag }));
        }
      }
    }

    // handleChangePage(params);
    if (params.page <= contentGroup.totalPages && params.page >= 1) {
      setIsLoading(true);
      handleLoadContentsNextPrevPage(params);
    }
  };

  const renderSkeleton = () => {
    const itemsPerPage = showPagination ? pageSize : contentGroup.itemSize * (contentGroup.isWrapLine ? 1 : contentGroup.numRow);
    let numRows = Math.ceil((contentGroup.contents ? contentGroup.contents.length : itemsPerPage) / (below768 ? 3 : contentGroup.itemSize));
    numRows = numRows === 0 ? 1 : numRows;
    return <React.Fragment key={'renderSkeleton'}>
      {
        showPagination
          ? [...Array(contentGroup.contents ? contentGroup.contents.length : pageSize).keys()].map((skeleton, index) => (
            <div key={`skeleton-component-${skeleton}`} className={classNames([classes.contentWrapScale, classes.wrapSkeleton])}>
              <Skeleton height={`${heightSkeleton[index % 10]}px`} className={'skeleton-input-component'} />
            </div>
          ))
          : [...Array(numRows).keys()].map(item => (
            <div key={`skeleton-${item}`} className={classes.wrapSkeleton}>
              {
                [...Array(below768 ? 3 : contentGroup.itemSize).keys()].map((skeleton, index) => (
                  <Skeleton height={`${heightSkeleton[index % 10]}px`} key={`skeleton-component-${skeleton}`} className={'skeleton-input-component'} />
                ))
              }
            </div>
          ))
      }
    </React.Fragment>;
  };

  const renderSkeletIsInfinityLoad = (isStart) => {
    if (isStart) {
      return (
        <Box className={`${classes.contentsRow}`}>
          {
            [...Array(below768 ? 3 : PAGINATION.size).keys()].map((skeleton, index) => (
              <div key={`SkeletIsInfinityLoad-isStart-${index}`} className={classes.contentWrapSkeleton}>
                <div className={`${classes.contentImageSkeleton}`}>
                  <Skeleton height={`${below768 ? heightSkeletonMobile[index % 10] : heightSkeleton[index % 10]}px`} key={`skeleton-component-${skeleton}`} className={'skeleton-input-component'} />
                </div>
              </div>
            ))
          }
        </Box>
      );
    }
    return <React.Fragment key={'renderSkeletIsInfinityLoad'}>
      {
        [...Array(below768 ? 3 : PAGINATION.size).keys()].map((skeleton, index) => (
          <div key={`SkeletIsInfinityLoad-${index}`} className={classes.contentWrapSkeleton}>
            <div className={`${classes.contentImageSkeleton}`}>
              <Skeleton height={`${below768 ? heightSkeletonMobile[index % 10] : heightSkeleton[index % 10]}px`} key={`skeleton-component-${skeleton}`} className={'skeleton-input-component'} />
            </div>
          </div>
        ))
      }
    </React.Fragment>;
  };

  const renderSkeletIncremental = () => {
    // const itemsPerPage = showPagination ? pageSize : contentGroup.itemSize * (contentGroup.isWrapLine ? 1 : contentGroup.numRow);
    // const numRows = Math.ceil((contentGroup.contents ? contentGroup.contents.length : itemsPerPage) / (below768 ? 3 : contentGroup.itemSize));
    return <React.Fragment key={'renderSkeletIncremental'}>
      {
        [...Array(PAGINATION.size).keys()].map((skeleton, index) => (
          <div key={`skeleton-component-${skeleton}`} style={{ justifyContent: 'center' }} className={classNames([classes.contentWrapScale, classes.wrapSkeleton])}>
            <Skeleton height={`${heightSkeleton[index % 10]}px`} className={'skeleton-input-component'}/>
          </div>
        ))
      }
    </React.Fragment>;
  };
  const renderFavoriteButton = (content) => {
    if (isLoggedIn) {
      return (
        <Box
          className={`${isMegreLayout && content.isFavorite ? classes.favoriteIcon3 : classes.favoriteIcon} favoriteIcon`}
          onClick={() => onSelectFavorite(content.id, content.isFavorite, {
            ...contentGroup,
            contentGroupId: contentGroup.id
          })}
          style={{
            color: isMegreLayout ? content.isFavorite ? '#fff' : '#585757' : '#F08828'
          }}
        >
          <div className="wrap-icon">
            {
              <IconBookMark isFavorite={!isMegreLayout && content.isFavorite}/>
            }
          </div>
        </Box>
      );
    }
  };

  const renderShowSubscriptionStatus = () => {
    if (showSubscriptionStatus && contentGroup.type === 1 && !isMobileApp) {
      const className = contentGroup.isSubscriptionPlan ? (contentGroup.isRegistered ? 'subscribed' : 'subscription') : 'free';
      const label = contentGroup.isSubscriptionPlan ? (contentGroup.isRegistered ? 'subscribed' : 'subscriptionRegister') : 'free';
      return (
        <span style={{ display: below768 ? 'blockk' : 'flex', whiteSpace: 'nowrap' }} className={`${below768 ? '' : 'tag ml-2 '}` + className}>
          {!below768 ? (className === 'subscribed' || className === 'free') ? <CheckCircleIcon/> : <CloseCircleFilled/> : <></>}
          {' ' + f('label.' + label)}
        </span>
      );
    }
    return null;
  };

  const checkScrollWidth = (newData) => {
    const element = document.getElementById(`contents-row-${contentGroup.id}`);
    if (element && element.scrollLeft + element.clientWidth + offsetLazyload >= element.scrollWidth) {
      if (newData.page + 1 <= newData.totalPages && !loadingByGroup[contentGroup.id]) {
        onChangePage(newData.page + 1);
      }
    }
  };

  useEffect(() => {
    if (loadContentActionType === 'PAGING' && page === 1 && page < totalPages && page < 2 && totalPages >= 2) {
      if (caseChangePage === CASE_CHANGE_PAGE.default) {
        const params = {
          page: 2,
          size: pageSize,
          caseChangePage: CASE_CHANGE_PAGE.default,
          contentGroup: contentGroup,
          isNext: true,
          isIncremental: false
        };
        handleLoadContentsNextPrevPage(params);
      }
    }
  }, [totalPages, contents, loadContentActionType, page]);
  useEffect(() => {
    if (contentGroup && (!contentGroup.contents || contentGroup.contents.length === 0)) {
      setIsInfinityLoad(contentGroup.loadContentActionType === LOAD_CONTENT_ACTION_TYPE.SCROLL && (isMegreLayout || isHomeLayout));
    }
  }, [contentGroup, pageSize, isClearData]);

  useEffect(() => {
    
    if (caseChangePage === CASE_CHANGE_PAGE.scroll && contentGroup && contentGroup.page < contentGroup.totalPages && !loadingByGroup[contentGroup.id]) {
      checkScrollWidth(contentGroup);
    }
  }, [contentGroup.contents]);

  useEffect(() => {
    if (!loadingByGroup[contentGroup.id]) {
      setIsLoading(false);
    }
  }, [loadingByGroup[contentGroup.id]]);

  const listener = useCallback(() => {
    const element = document.getElementById(`end-page-content-group-${contentGroup.id}`);
    if (showPagination && below768 && element && element.getBoundingClientRect() && contentGroup && contentGroup.totalPages > contentGroup.page) {
      const check = element.getBoundingClientRect().bottom <= window.innerHeight + offsetLazyload;
      if (check) {
        onChangePage(contentGroup.page + 1);
      }
    }
  }, [contentGroup]);

  const debounceListener = _.debounce(listener, 500);

  useEffect(() => {
    if (showPagination && below768 && contentGroup && contentGroup.totalPages > contentGroup.page) {
      setTimeout(() => {
        listener();
      }, 100);
      window.addEventListener('scroll', debounceListener, true);
      return () => {
        window.removeEventListener('scroll', debounceListener, true);
      };
    }
  }, [showPagination, contentGroup.page]);

  return (
    <div id={`content-group-${contentGroup.id}`} style={{ margin: isMegreLayout ? '1.4rem 0' : '' }}>
      <div className={classes.title} onClick={() => onSelectContentGroup(contentGroup.id, `${contentGroupId}` === `${contentGroup.id}` && !contentId)}>
        <span style={{ display: 'flex', alignItems: below768 ? 'flex-start' : 'center', flexDirection: below768 ? 'column' : 'row' }}>
            <span style={{ wordBreak: 'break-word', display: 'flex' }}>{contentGroup.name}</span>
            { renderShowSubscriptionStatus() }
        </span>
        <Button className={classNames({ 'button-more-less': true })} style={{ display: 'flex', alignItems: 'center', padding: '0.5rem 1rem' }}>
            {isShowDetail ? f('button.less') : f('button.more')}
            <RightOutlined className='ml-1'/>
        </Button>
      </div>
      <div className={classes.contents}>
        {
          caseChangePage === CASE_CHANGE_PAGE.default && !showPagination && contentGroup.contents && contentGroup.contents.length > 0 && (
            <React.Fragment>
              <span
                className={`${classes.iconPaging} ${!isLoading && dataPrePage ? classes.pointer : ''} ${classes.iconPrevPage} ${contentGroup.page <= 1 && classes.disabled}`}
                onClick={() => !isLoading && dataPrePage && onChangePage(contentGroup.page - 1)}
              >
                <span style={{ width: '100%', textAlign: 'center' }}><LeftOutlined/></span>
              </span>
              <span
                className={`${classes.iconPaging} ${!isLoading && dataNextPage ? classes.pointer : ''} ${classes.iconNextPage} ${contentGroup.totalPages <= contentGroup.page && classes.disabled}`}
                onClick={() => !isLoading && dataNextPage && onChangePage(contentGroup.page + 1)}
              >
                <span style={{ width: '100%', textAlign: 'center' }}><RightOutlined/></span>
              </span>
            </React.Fragment>
          )
        }
        {
          showPagination && caseChangePage !== CASE_CHANGE_PAGE.scroll
            ? <div className={classes.allContents}>
              {renderContentsPagination()}
            </div>
            : renderRowContents()
        }
        {
            showPagination && !below768 &&
            <Box display={'flex'}>
              <Select
                className={classes.selectNumItem}
                options={optionNumItem}
                placeholder={"Select subscription type"}
                style={{ width: '72px' }}
                value={optionNumItem.filter(item => item.value === pageSize)[0]}
                onChange={option => {
                  changePageSize(option.value);
                }}
              />
              <CustomPagination
                page={contentGroup.page}
                totalPages={contentGroup.totalPages}
                onChangePage={(page: number) => {
                  onChangePage(page, pageSize);
                }}
              />
            </Box>
        }
      </div>
      { showPagination && <div id={`end-page-content-group-${contentGroup.id}`}/> }
    </div>
  );
};

export default ContentListRender;