"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,
  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 HomeSubscriptionPlan from "@/components/home/home-subscription-plan";
import HomeNotifications from "./home-notifications";

const offsetLazyload = 200;
export default function HomePageRender(props: any) {
  
  const t = useTranslations("");
  const dispatch = useAppDispatch();
  const router = useRouter();
  const mounted = useMounted();
  const searchParams = useSearchParams();
  
//   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 contentGroupByContentId = useAppSelector(getContentGroupByContentId);
  const isLoggedIn = !!useAppSelector(getIsAuthenticated);
  const layoutViewPage = useAppSelector(getLayoutViewPage);
  const hashtagList = useAppSelector(getHashtagUser);
  const isLoadingHashtag = useAppSelector(getIsLoadingHashtag);
  const { contentLayoutDetail } = useAppSelector(getContentDetailSetting);

  // state in home layout
  const sortOrder = useAppSelector(getSortOrder);
  const showFavorite = useAppSelector(getShowFavorite);
  const searchRequest = useAppSelector(getSearchRequest);
  const listSorts = useAppSelector(getAllSort);
  const servicePath = useAppSelector(getServicePath);
  const bodySetting = useAppSelector(getBodySetting);

  const [selectHashtags, setSelectHashtags] = useState<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 useStyle = makeStyles()(() => {
    // const pathname = mounted ? window.location.pathname : '';
    // const isBelow768 = getBelow768();
    
    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'
        }
      }
    );
  });
  const { classes } = useStyle();
  
  const params = useParams();
  const contentGroupId = params.contentGroupId || searchParams.get('contentGroupId');
  const User_id = searchParams.get('User_id');
  
  


  const selectedContentGroup = contentGroups.find(item => `${contentGroupId}` === `${item.id}`) || {} as any;
  const { type } = selectedContentGroup;

  const isDefaultGroup = type && type !== CONTENT_GROUP_TYPE.NORMAL;




















  // 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));
  };
  const handleLoadContentByHashtag = (contentGroup: any, hashtagList: string[], page?: number, size?: number,  isNewSearch?: boolean) => {
    const numItems = contentGroup.isWrapLine ? contentGroup.itemSize : contentGroup.numRow * contentGroup.itemSize;
    const request = {
      params: {
        contentGroupId: contentGroup.id,
        page: page,
        size: size || numItems,
        isNewSearch: !!isNewSearch,
        ...sortOrder
      },
      data: { ids: hashtagList }
    };
    dispatch(loadContentByHashtag(request));
  };
  const onSelectContentGroup = (contentGroupId, isBackHome) => {
    if (isBackHome) {
      router.push(`${servicePath ? '/'+servicePath : ''}`);
    } else {
      router.push(`${servicePath ? '/'+servicePath : ''}/${contentGroupId}`);
    }
    // const cache = searchRequest;
    // setCacheSearchRequest({ searchRequest: cache });
  };
  const changeSort = (sort: any) => {
    clearContents();
    dispatch(setSortOrder(sort));
  };











  
  // 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);

  
  useEffect(() => {
    if (contentGroupId && selectedContentGroup && selectedContentGroup.id) {
      !isLoadingHashtag && handleLoadContent(selectedContentGroup, 1, pageSize);
    }
  }, [contentGroupId]);

  useEffect(() => {
    if (contentGroups.length > 0) {
      setTimeout(() => {
        listener();
      }, 100);
    }
  }, [contentGroups.length]);

  useEffect(() => {
    window.addEventListener('scroll', debounceListener, true);
    return () => {
      window.removeEventListener('scroll', debounceListener, true);
    };
  }, [contentGroups, searchRequest, selectHashtags]);
  useEffect(() => {
    if (contentGroupByContentId && contentGroupByContentId.length > 0) {
      setTimeout(() => {
        listener();
      }, 100);
    }
  }, [contentGroupByContentId]);

  useEffect(() => {
    if (!selectedContentGroup.id && contentGroups && contentGroups.length > 0) {
      setIsInitSort(true);
    }
  }, [contentGroups]);
  useEffect(() => {
    if (contentGroups && contentGroups.length > 0 && sortOrder && isInitSort) {
      if (selectedContentGroup.id) {
        handleLoadContent(selectedContentGroup, selectedContentGroup.page, pageSize);
      }
    }
  }, [sortOrder]);
  useEffect(() => {
    if (contentGroups && contentGroups.length > 0) {
      if (selectedContentGroup.id) {
        handleLoadContent(selectedContentGroup, 1, pageSize);
      }
    }
  }, [pageSize]);

  useEffect(() => {
    if (selectHashtags.length > 0) {
      for (const contentGroup of contentGroups) {
        const numItems = selectedContentGroup.id
          ? pageSize
          : contentGroup.isWrapLine ? contentGroup.itemSize : contentGroup.numRow * contentGroup.itemSize;
        const pageNum = 1;
        if (contentGroup.id === contentGroups[0].id) {
          handleLoadContentByHashtag(contentGroup, selectHashtags, pageNum, numItems, true);
        } else {
          handleLoadContentByHashtag(contentGroup, selectHashtags, pageNum, numItems, false);
        }
      }
    } else {
      for (const contentGroup of contentGroups) {
        let numItems = selectedContentGroup.id
          ? pageSize
          : (contentGroup.isWrapLine ? contentGroup.itemSize : contentGroup.numRow * contentGroup.itemSize);

        if (contentGroup.loadContentActionType === LOAD_CONTENT_ACTION_TYPE.SCROLL && !selectedContentGroup.id) {
          numItems = 10;
        }
        if ((contentGroup.contents && !contentGroup.isLoading) || (contentGroup.isReload && contentGroup.isLoading)) {
          handleLoadContent(contentGroup, 1, numItems);
        }
      }
    }
  }, [selectHashtags, selectHashtags.length]);

  const navigateContentDetail = (_contentId, _contentGroupId) => {
    resetDownloadContentId();
    // const cache = searchRequest;
    // setCacheSearchRequest({ searchRequest: cache });
    router.push(`${servicePath ? '/'+servicePath : ''}/${_contentGroupId}/${_contentId}`);
  };
  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 handleLoadContentsNextPrevPage = ({ page, contentGroup, size, isNext, isIncremental, caseChangePage }) => {
    
    const isInfinityLoad = contentGroup.loadContentActionType === LOAD_CONTENT_ACTION_TYPE.SCROLL && (layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT.id || isMegreLayout);
    const ids = selectHashtags;
    
    
    const numItems = contentGroup.isWrapLine ? contentGroup.itemSize : contentGroup.numRow * contentGroup.itemSize;
    const params:any = {
      contentGroupId: contentGroup.id,
      contentGroup: contentGroup,
      page: page,
      path: servicePath,
      size: (isInfinityLoad ? PAGINATION.size : size || contentGroup.numRow * contentGroup.itemSize) || numItems,
      isNext,
      caseChangePage,
      isIncremental,
      ids: selectHashtags || [],
      ...sortOrder
    };
    if (ids && ids.length > 0) {
      params.type = TYPE_PRE_NEXT_PAGE.SEARCH_CONTENT_BY_HASHTAG;
    } else {
      params.type = TYPE_PRE_NEXT_PAGE.GET_CONTENT_BY_CONTENT_GROUP;
    }
    return dispatch(loadContentsNextPrevPage(params));
  };
  const changePageSize = (pageSize) => {
    clearContents();
    setPageSize(pageSize);
  };

  const handleChangeFavoriteContent = (contentId, isFavorite, contentGroup) => {
    const params = {
      contentGroupId: contentGroup ? contentGroup.contentGroupId : contentGroupId || ''
    };
    if (isFavorite) {
      dispatch(removeFavoriteContent({ contentId: contentId, contentGroup: params }));
    } else {
      dispatch(addFavoriteContent({ contentId: contentId, contentGroup: params }));
    }
  };

  const onSortLayout3 = (sort, asc) => {
    const params = { sortField: sort, sort: asc };
    changeSort(params);
  };

  const handleSearchByHashTag = (data) => {
    setSelectHashtags(data);
  };
  
  return (
    <div className={classes.homeContents + ` search-page`} id="homeContents">
      {/* show hash Tags */}
      {
        hashtagList.length > 0 && !selectedContentGroup.id &&
        <div style={{ margin: '10px 0px 10px 0px' }}>
          <ChoiceHashTagField
            hashtagIds={selectHashtags}
            disabled={isLoadingHashtag}
            options={hashtagList}
            name="hashtagIds"
            minWidth={100}
            isMultiSelect={isMultipleSelectHashtag}
            onSelected={(value: any[]) => {
              !isLoadingHashtag && handleSearchByHashTag(value);
            }}
          />
        </div>
      }
      {/* show Subscriptio Status */}
      {!isMobileApp && viewSettings.showSubscriptionStatus && !selectedContentGroup.id && !contentGroupId && <HomeSubscriptionPlan isMegreLayout={isMegreLayout} />}
      {viewSettings.notificationOn && isMegreLayout && <HomeNotifications/>}
      
      {/* {
        isMegreLayout &&
          <div style={{ minWidth: '200px', display: 'flex', justifyContent: 'flex-start', alignItems: 'center', marginLeft: below768 ? '10px' : '0px' }}>
            <SortSearchResult
              // data={searchSetting.sortedContentFields}
              listSortField={listSorts}
              valueSort={sortOrder.sortField}
              isAsc={sortOrder.sort}
              onSort={onSortLayout3}
            />
          </div>
      } */}
      {/* content is not selectedContentGroup */}
      {
        !selectedContentGroup.id && selectHashtags.length === 0 && contentGroups && contentGroups.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}
                isLoggedIn={isLoggedIn}
                onSelectFavorite={handleChangeFavoriteContent}
                sortOrder={sortOrder}
                dataNextPage={listDataNextPage[item.id]}
                dataPrePage={listDataPrePage[item.id]}
                isShowDetail={false}
                showFavorite={showFavorite}
                showSubscriptionStatus={viewSettings.showSubscriptionStatus}
                handleLoadContentsNextPrevPage={handleLoadContentsNextPrevPage}
                selectHashtags={selectHashtags}
              />
            );
          }
        })
      }
      {/* content is selectedContentGroup*/}
      {
        !selectedContentGroup.id && selectHashtags.length > 0 && contentGroups.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}
                isLoggedIn={isLoggedIn}
                onSelectFavorite={handleChangeFavoriteContent}
                sortOrder={sortOrder}
                dataNextPage={listDataNextPage[item.id]}
                dataPrePage={listDataPrePage[item.id]}
                isShowDetail={false}
                showFavorite={showFavorite}
                showSubscriptionStatus={viewSettings.showSubscriptionStatus}
                handleLoadContentsNextPrevPage={handleLoadContentsNextPrevPage}
                selectHashtags={selectHashtags}
              />
            );
          }
        })
      }

      {
        selectedContentGroup.id && contentGroups.map(item => {
          if (selectedContentGroup.id === item.id) {
            return (
              <ContentListRender
                key={`content-group-${item.id}`}
                contentGroup={item}
                handleChangePage={handleChangePage}
                handleLoadDetail={navigateContentDetail}
                onSelectContentGroup={onSelectContentGroup}
                showPagination={true}
                pageSize={pageSize}
                changePageSize={changePageSize}
                isLoggedIn={isLoggedIn}
                dataNextPage={listDataNextPage[item.id]}
                dataPrePage={listDataPrePage[item.id]}
                onSelectFavorite={handleChangeFavoriteContent}
                sortOrder={sortOrder}
                isShowDetail={!!selectedContentGroup.id}
                showFavorite={showFavorite}
                showSubscriptionStatus={viewSettings.showSubscriptionStatus}
                handleLoadContentsNextPrevPage={handleLoadContentsNextPrevPage}
                loadContentsNextPrevPage={loadContentsNextPrevPage}
                selectHashtags={selectHashtags}
              />
            );
          }
        })
      }
    </div>
  );

}
