"use client"

import { useParams, useRouter, useSearchParams } from "next/navigation";
import { CONTENT_DETAIL_LAYOUT, CONTENT_GROUP_TYPE, LAYOUT_SETTING, LOAD_CONTENT_ACTION_TYPE, PAGINATION, TYPE_PRE_NEXT_PAGE } from "@/lib/appConstant";
import { getBodySetting, getContentDetailSetting, getLayoutViewPage, getServicePath, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { ServiceViewSettings } from "@/types/serviceAdmin";
import { useTranslations } from "use-intl";
import { useEffect, useState } from "react";
import {
  addFavoriteContent,
  clearContents,
  getContentGroupByContentId,
  getIsContentInfoLoad,
  getIsLoadingHashtag,
  getListDataNextPage,
  getListDataPrePage,
  getPublicContentGroups,
  getSearchRequest,
  getShowFavorite,
  getSortOrder,
  loadContentByContentGroup,
  loadContentByHashtag,
  loadContentsNextPrevPage,
  loadPublicContentGroups,
  removeFavoriteContent,
  resetDownloadContentId,
  setCacheSearchRequest,
  setSortOrder,
} from "@/lib/redux/features/content";
import { getAuthInfo,  getIsAuthenticated,  getIsMobileApp } from "@/lib/redux/features/auth";
import { getHashtagUser, getPublicHashtag } from "@/lib/redux/features/hashtag";
import { getAllSort } from "@/lib/redux/features/sort";
import { ContentGroupMapRender } from "@/types/content-group";
import * as _ from 'lodash';
// import { GetContentByHashtagRequest, GetContentByHashtagRequestData } from "@/types/content";
import { useMounted } from "@/hooks/useMounted";
import ChoiceHashTagField from "@/components/ui/choice-hashtag-field";
import ContentListRender from "@/components/content/content-list";
import useResponsive from "@/hooks/useResponsive";
import { makeStyles } from "tss-react/mui";
import { Col, Row, Skeleton } from "antd";
import ContentDetailsRender from "./content-details-render";
import { setShowBanner } from "@/lib/redux/features/layout";

const offsetLazyload = 200;
type PropsType = { viewSettings?: ServiceViewSettings };
type MakeStylesType = {
  isMegreLayout: boolean;
  contentLayoutDetail: any;
};
const useStyle = makeStyles<MakeStylesType>()((theme, { isMegreLayout, contentLayoutDetail }) => {
  return (
    {
      homeContents: {
        width: isMegreLayout ? 'calc(100%)' : 'calc(100% - 200px)',
        flex: '1 0 auto',
        height: contentLayoutDetail === CONTENT_DETAIL_LAYOUT.LIST_SAME_GROUP ? 'fit-content' : ''
      },
      bold: {
        fontWeight: 700
      },
      searchTab: {
        '& label': {
          fontWeight: 700
        }
      },
      navlink: {
        border: 'none!important',
        borderRadius: '0!important',
        backgroundColor: 'unset!important',
        color: '#fff!important'
      },
      tabContent: {
        border: '2px solid #d0d0d0',
        borderTop: 0,
        backgroundColor: '#fff',
        padding: '1rem'
      },
      totalResults: {
        fontSize: '1rem',
        marginBottom: '0.5rem'
      },
      hidden: {
        display: 'none'
      },
      sortIcon: {
        fontSize: '1.5rem',
        marginLeft: '0.5rem'
      },
      disabled: {
        opacity: 0.6,
        pointerEvents: 'none'
      }
    }
  );
});
export default function ContentDetailsPageRender(props: PropsType) {
  
  const t = useTranslations("");
  const dispatch = useAppDispatch();
  const router = useRouter();
  const mounted = useMounted();
  const searchParams = useSearchParams();
  const { contentId, contentGroupId } = useParams();
  
//   const { below768, getBelow768 } = useResponsive();
  const viewSettings = useAppSelector(getViewSettings) as ServiceViewSettings;
  const listDataNextPage = useAppSelector(getListDataNextPage) as any || {};
  const listDataPrePage = useAppSelector(getListDataPrePage) as any || {};
  const isMobileApp = useAppSelector(getIsMobileApp);
  const contentGroups = useAppSelector(getPublicContentGroups) as ContentGroupMapRender[] || [] as ContentGroupMapRender[];

// state in home page
  const sortOrder = useAppSelector(getSortOrder);
  const contentGroupByContentId = useAppSelector(getContentGroupByContentId);
  const isLoggedIn = !!useAppSelector(getIsAuthenticated);
  const layoutViewPage = useAppSelector(getLayoutViewPage);
  const { contentLayoutDetail } = useAppSelector(getContentDetailSetting);

  // state in home layout
  const showFavorite = useAppSelector(getShowFavorite);
  const listSorts = useAppSelector(getAllSort);
  const servicePath = useAppSelector(getServicePath);
  const bodySetting = useAppSelector(getBodySetting);
  const isLoaded = useAppSelector(getIsContentInfoLoad);
  

  const [selectHashtags, setSelectHashtags] = useState([] as any[]);
  const [isInitSort, setIsInitSort] = useState(false);
  const [pageSize, setPageSize] = useState(10);
  const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;


  const { layoutSettingResponse, isMultipleSelectHashtag } = viewSettings;

  const { classes } = useStyle({ isMegreLayout, contentLayoutDetail });
  
  // const contentGroupId = searchParams.get('contentGroupId');
  const User_id = searchParams.get('User_id');


  const showContentGroupByContentId = contentLayoutDetail === CONTENT_DETAIL_LAYOUT.LIST_SAME_GROUP;




















  // const listDataNextPage = useSelector(getListDataNextPage) || {};
  // const listDataPrePage = useSelector(getListDataPrePage) || {};
  const isFulltextSearch = '';

  const offsetLazyload = 200;

// In Layout
  const handleLoadContent = (contentGroup: any, page: number, size?: number) => {
    const numItems = contentGroup.isWrapLine ? contentGroup.itemSize : contentGroup.numRow * contentGroup.itemSize;
    const params = {
      contentGroupId: contentGroup.id,
      page: page,
      path: servicePath,
      size: size || numItems,
      ...sortOrder
    };
    dispatch(loadContentByContentGroup(params));
  };












  
  // In home
//   const listener = (newSearch?: any) => {
//     for (const contentGroup of contentGroups) {
//       if ((!contentGroup.contents && !contentGroup.isLoading) || (contentGroup.isReload && !contentGroup.isLoading)) {
//         const isInfinityLoad = contentGroup.loadContentActionType === LOAD_CONTENT_ACTION_TYPE.SCROLL && (layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT.id || isMegreLayout);
//         const element = document.getElementById(`content-group-${contentGroup.id}`) || {} as any;
//         const { offsetTop, clientHeight } = element;
//         const numItems =  isInfinityLoad
//           ? PAGINATION.size
//           : (contentGroup.isWrapLine ? contentGroup.itemSize : contentGroup.numRow * contentGroup.itemSize);
//         const pageNum = contentGroup.page ? contentGroup.page : 1;
//         const top = offsetTop;
//         const height = clientHeight;
//         const intersectionHeight = window.innerHeight || document.documentElement.clientHeight;
//         const intersectionTop = window.pageYOffset || document.documentElement.offsetTop;
//         const checkVisibleTop = top >= intersectionTop - offsetLazyload && top <= intersectionTop + intersectionHeight + offsetLazyload;
//         const checkVisibleBottom = top + height >= intersectionTop && top + height <= intersectionTop + intersectionHeight;
//         if (checkVisibleTop || checkVisibleBottom) {
//           if (selectHashtags.length > 0) {
//             if (contentGroup.id === contentGroups[0].id) {
//               handleLoadContentByHashtag(contentGroup, selectHashtags, pageNum, numItems, newSearch);
//             } else {
//               handleLoadContentByHashtag(contentGroup, selectHashtags, pageNum, numItems, false);
//             }
//           } else {
//             handleLoadContent(contentGroup, pageNum, numItems);
//           }
//         }
//       }
//     }
//   };

//   const debounceListener = _.debounce(listener, 500);

  


  const navigateContentDetail = (_contentId, _contentGroupId) => {
    resetDownloadContentId();
    // const cache = searchRequest;
    // setCacheSearchRequest({ searchRequest: cache });
    router.push(`${servicePath ? '/'+servicePath : ''}/${_contentGroupId}/${_contentId}`);
  };
  

  const handleChangeFavoriteContent = (contentId: string, isFavorite: boolean, contentGroup: any) => {
    const params = {
      contentGroupId: contentGroup ? contentGroup.contentGroupId : contentGroupId || ''
    };
    if (isFavorite) {
      removeFavoriteContent({ contentId: contentId, contentGroup: params });
    } else {
      addFavoriteContent({ contentId: contentId, contentGroup: params });
    }
  };

  const handleChangePage = ({ page, contentGroup, size }) => {
    if (contentGroup) {
      const isInfinityLoad = contentGroup.loadContentActionType === LOAD_CONTENT_ACTION_TYPE.SCROLL && (layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT.id || layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id);
      const pageSize = isInfinityLoad ? PAGINATION.size : size || contentGroup.numRow * contentGroup.itemSize;
      handleLoadContent(contentGroup, page, pageSize);
    } else {
      handleLoadContent(contentGroup, page, PAGINATION.size);
    }
  };
  const onSelectContentGroup = (contentGroupId: any, isBackHome: any) => {
    if (isBackHome) {
      router.push(`${servicePath ? '/'+servicePath : ''}/`);
    } else {
      router.push(`${servicePath ? '/'+servicePath : ''}/${contentGroupId}`);
    }
  };


  if (!mounted) {
    return null;
  } 
  
  return (
    <div className={classes.homeContents + ` search-page`} id="homeContents">
        
        <ContentDetailsRender
            onSelectFavorite={handleChangeFavoriteContent}
            showFavorite={showFavorite}
        />
        {
            !isLoaded && showContentGroupByContentId && contentGroups.filter(cg => contentGroupByContentId.includes(cg.id)).map(item => {
                if (item.type === CONTENT_GROUP_TYPE.NORMAL) {
                    return (
                        <ContentListRender
                            key={`content-group-${item.id}`}
                            contentGroup={item}
                            handleChangePage={handleChangePage}
                            handleLoadDetail={navigateContentDetail}
                            onSelectContentGroup={onSelectContentGroup}
                            showPagination={false}
                            dataNextPage={listDataNextPage[item.id]}
                            dataPrePage={listDataPrePage[item.id]}
                            isLoggedIn={isLoggedIn}
                            isShowDetail={false}
                            showFavorite={showFavorite}
                            onSelectFavorite={handleChangeFavoriteContent}
                            showSubscriptionStatus={viewSettings.showSubscriptionStatus}
                            loadContentsNextPrevPage={loadContentsNextPrevPage}
                        />
                    );
                }
            })
        }
    </div>
  );

}
