"use client"

import { useParams, useRouter, useSearchParams } from "next/navigation";
import { CONTENT_DETAIL_LAYOUT, CONTENT_GROUP_TYPE, LAYOUT_SETTING, LOAD_CONTENT_ACTION_TYPE, PAGINATION, TAB_TYPE, TYPE_PRE_NEXT_PAGE } from "@/lib/appConstant";
import { getBodySetting, getContentDetailSetting, getLayoutViewPage, getSearchTabs, getServicePath, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { SearchTabResponse, ServiceViewSettings } from "@/types/serviceAdmin";
import { useTranslations } from "use-intl";
import { useEffect, useState } from "react";
import {
  addFavoriteContent,
  clearContents,
  doSearchContentByContentGroup,
  doSearchContentFullText,
  getCacheSearchRequest,
  getContentGroupByContentId,
  getIsLoadingHashtag,
  getListDataNextPage,
  getListDataPrePage,
  getPublicContentGroups,
  getShowFavorite,
  getSortOrder,
  loadContentByContentGroup,
  loadContentByHashtag,
  loadContentsNextPrevPage,
  removeFavoriteContent,
  resetDownloadContentId,
  setCacheSearchRequest,
  setSearchRequestFullTextSearch,
  setSortOrder,
} from "@/lib/redux/features/content";
import { getAuthInfo,  getIsAuthenticated,  getIsMobileApp } from "@/lib/redux/features/auth";
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 ContentListRender from "@/components/content/content-list";
import { makeStyles } from "tss-react/mui";
import SearchBoxForm from "../forms/tabs-search-box-form";
// import { getIsFullTextSearch, setFullTextSearch, setIsFullTextSearch, setSearchRequest } from "@/lib/redux/features/search-page";
import { formatDate } from "@/lib/utils";
import { getFulltextSearch, getIsFullTextSearch, getSearchRequest, setFullTextSearch, setIsFullTextSearch, setSearchRequest } from "@/lib/redux/features/search-page";
import SortSearchResult from "../search/sort-search-result";
import useResponsive from "@/hooks/useResponsive";

const offsetLazyload = 200;
type PropsType = { viewSettings: ServiceViewSettings };
type MakeStylesType = {
  layoutViewPage: any;
  contentLayoutDetail: any;
};



const useStyle = makeStyles<MakeStylesType>()((theme, { contentLayoutDetail, layoutViewPage }) => {
  return (
    {
      homeContents: {
        width: layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id ? '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
        }
      },
      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 HomeSearchPageRender(props: PropsType) {
  
  const t = useTranslations("");
  const dispatch = useAppDispatch();
  const router = useRouter();
  const mounted = useMounted();
  const searchParams = useSearchParams();
  
  const { below768 } = 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 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 searchTabs = useAppSelector(getSearchTabs);

  const cacheSearchRequest = useAppSelector(getCacheSearchRequest);
  const fulltextSearch = useAppSelector(getFulltextSearch);
  const isFulltextSearch = useAppSelector(getIsFullTextSearch);

  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({ contentLayoutDetail, layoutViewPage });
  
  const params = useParams();
  const contentGroupId = searchParams.get('contentGroupId');
  
  console.log('isFulltextSearch: ', isFulltextSearch);
  console.log('fulltextSearch: ', fulltextSearch);
  

  const selectedContentGroup = contentGroups.find(item => `${contentGroupId}` === `${item.id}`) || {} as any;
  const { type } = selectedContentGroup;

  const isDefaultGroup = type && type !== CONTENT_GROUP_TYPE.NORMAL;

  const hideSearchResult = (!searchRequest || searchRequest.length <= 0) && !fulltextSearch;

  














  // const listDataNextPage = useSelector(getListDataNextPage) || {};
  // const listDataPrePage = useSelector(getListDataPrePage) || {};

  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) => {
    dispatch(clearContents());
    dispatch(setSortOrder(sort));
  };
  const handleSearchContent = (contentGroup: ContentGroupMapRender, page: number, size: number, fulltextSearchValue: any, searchValues: any, isSearchFullText?: boolean, isNewSearch?: boolean) => {
    const numItems = contentGroup ? (contentGroup.isWrapLine ? contentGroup.itemSize : contentGroup.numRow * contentGroup.itemSize) : PAGINATION.size;
   
    if (fulltextSearchValue && isSearchFullText) {
      const request = {
        searchKey: fulltextSearchValue,
        contentGroupId: contentGroup ? contentGroup.id : null,
        pagination: {
          page: page,
          size: size || numItems,
          isNewSearch: !!isNewSearch,
          ...sortOrder
        }
      };
      if (sortOrder && sortOrder.sortField === 12) {
        delete request.pagination.sortField;
      }
      console.log('request: ', request);
      
      dispatch(doSearchContentFullText({
        ...request
      }));
    } else {
      if (isFulltextSearch) {
        const request = {
          searchKey: fulltextSearchValue,
          contentGroupId: contentGroup ? contentGroup.id : null,
          pagination: {
            page: page,
            size: size || numItems,
            isNewSearch: !!isNewSearch,
            ...sortOrder
          }
        };
        if (sortOrder && sortOrder.sortField === 12) {
          delete request.pagination.sortField;
        }
        console.log(' >>>> request: ', request);
        dispatch(doSearchContentFullText({
          ...request
        }));
      } else {
        const params = {
          searchRequests: searchValues,
          contentGroupId: contentGroup ? contentGroup.id : null,
          pagination: {
            page: page,
            size: size || numItems,
            isNewSearch: !!isNewSearch,
            ...sortOrder
          }
        };
        if (sortOrder && sortOrder.sortField === 12) {
          delete params.pagination.sort;
          delete params.pagination.sortField;
        }
        dispatch(doSearchContentByContentGroup(params));
      }
    }
  };
  const handleChangeSearchRequest = (form) => {
    if (form.tabType === TAB_TYPE.FULLTEXT_SEARCH.id) {
      dispatch(setFullTextSearch(form.value));
      dispatch(setIsFullTextSearch(true));
    } else {
      let searchRequests: any[] = [];
      for (const item in form) {
        let value = form[item];

        if (Array.isArray(value) && value.length > 0) {
          let str = '';
          for (let item of value) {
            if (!item) {
              item = '';
            }
            if (item && item.value) {
              str += `${str === '' ? '' : ','}${item.value}`;
            } else {
              str += `${str === '' ? '' : ','}${item === '' ? '' : formatDate(item, 'YYYY/MM/DD')}`;
            }
          }
          value = str;
        }

        if (value && value !== '' && value.length !== 0) {
          const param: any = {
            value: value.value || value.value === '' ? value.value : value,
            searchBoxId: parseInt(item.replace('search', ''), 10)
          };
          if (form[item] && form[item].contentGroupIdList) {
            param.contentGroupIdList = form[item].contentGroupIdList;
          }
          if (param.searchBoxId || param.searchBoxId === 0) {
            searchRequests = [...searchRequests, param];
          }
        }
      }
      console.log('searchRequests: ', searchRequests);
      
      dispatch(setSearchRequest(searchRequests));
    }
  };
  
  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 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: [],
      type: TYPE_PRE_NEXT_PAGE.GET_CONTENT_BY_CONTENT_GROUP,
      ...sortOrder
    };
    return dispatch(loadContentsNextPrevPage(params));
  };











  
  // In home
   
  const listener = (newSearch?: boolean) => {
    
    for (const contentGroup of contentGroups) {
      if ((!contentGroup.contents && !contentGroup.isLoading) || (contentGroup.isReload && !contentGroup.isLoading)) {
        console.log(' >>>> here 0: ');
        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 = selectedContentGroup.id
          ? pageSize
          : (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 (contentGroup.type === CONTENT_GROUP_TYPE.NORMAL) {
            if (contentGroup.id === contentGroups[0].id) {
              handleSearchContent(contentGroup, pageNum, numItems, fulltextSearch, searchRequest, isFulltextSearch, newSearch);
            } else {
              handleSearchContent(contentGroup, pageNum, numItems, fulltextSearch, searchRequest, isFulltextSearch, false);
            }
          } else {
            handleLoadContent(contentGroup, pageNum, numItems);
          }
        }
      }
    }
  };

  const debounceListener = _.debounce(listener, 500);

  useEffect(() => {
    if (cacheSearchRequest) {
      dispatch(setCacheSearchRequest(cacheSearchRequest.searchRequest));
    }
  }, []);

  useEffect(() => {
    if (contentGroupId && selectedContentGroup && selectedContentGroup.id) {
      if (selectedContentGroup.type === CONTENT_GROUP_TYPE.NORMAL) {
        handleSearchContent(selectedContentGroup, 1, pageSize, fulltextSearch, searchRequest, isFulltextSearch, false);
      } else {
        !isLoadingHashtag && handleLoadContent(selectedContentGroup, 1, pageSize);
      }
    }
  }, [contentGroupId]);

  useEffect(() => {
    setTimeout(() => {
      listener();
    }, 100);
  }, [contentGroups]);

  useEffect(() => {
    dispatch(clearContents());
    setTimeout(() => {
      listener(true);
    }, 100);
  }, [fulltextSearch, searchRequest]);

  useEffect(() => {
    window.addEventListener('scroll', debounceListener, true);
    return () => {
      window.removeEventListener('scroll', debounceListener, true);
    };
  }, [contentGroups, searchRequest, fulltextSearch]);
  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) {
        if (!isDefaultGroup) {
          handleSearchContent(selectedContentGroup, selectedContentGroup.page, pageSize, fulltextSearch, searchRequest, isFulltextSearch)
        } else {
          handleLoadContent(selectedContentGroup, selectedContentGroup.page, pageSize)
        }
      }
    }
  }, [sortOrder]);
  useEffect(() => {
    if (contentGroups && contentGroups.length > 0) {
      if (selectedContentGroup.id) {
        if (!isDefaultGroup) {
          handleSearchContent(selectedContentGroup, 1, pageSize, fulltextSearch, searchRequest, isFulltextSearch)
        } else {
          handleLoadContent(selectedContentGroup, 1, pageSize)
        }
      }
    }
  }, [pageSize]);

  const navigateContentDetail = (_contentId, _contentGroupId) => {
    resetDownloadContentId();
    const cache = searchRequest;
    setCacheSearchRequest({ searchRequest: cache });
    router.push(`${servicePath ? '/'+servicePath : ''}/${_contentGroupId}/${_contentId}`);
  };
  
  const onSortMegreLayout = (sort, asc) => {
    const params = { sortField: sort, sort: asc };
    changeSort(params);
  };

  const handleChangePage = ({ page, contentGroup, size }) => {
    if (contentGroup) {
      const isInfinityLoad = contentGroup.loadContentActionType === LOAD_CONTENT_ACTION_TYPE.SCROLL && (layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT.id || isMegreLayout);
      const pageSize = isInfinityLoad ? PAGINATION.size : size || contentGroup.numRow * contentGroup.itemSize;
      if (!isDefaultGroup) {
        handleSearchContent(contentGroup, page, pageSize, fulltextSearch, searchRequest)
      } else {
        handleLoadContent(contentGroup, page, pageSize)
      }
    } else {
      if (!isDefaultGroup) {
        handleSearchContent(contentGroup, page, PAGINATION.size, fulltextSearch, searchRequest, isFulltextSearch)
      } else {
        handleLoadContent(contentGroup, page, PAGINATION.size)
      }
    }
  };
  const changePageSize = (pageSize) => {
    dispatch(clearContents());
    setPageSize(pageSize);
  };

  const onSearch = (searchRequest: any, tab: SearchTabResponse) => {
    if (tab.type === TAB_TYPE.FULLTEXT_SEARCH.id) {
      // setIsSearchFullText(true);
      dispatch(setIsFullTextSearch(true));
      let searchValue;
      for (const key in searchRequest) {
        searchValue = searchRequest[key];
      }
      const newObject: any = {};
      newObject.value = searchValue;
      newObject.searchBoxId = Number(`${Object.keys(searchRequest)[0].replace('search', '')}`);
      const newCache: any[] = [];
      newCache.push(newObject);
      dispatch(setSearchRequestFullTextSearch(newCache));
      handleChangeSearchRequest({
        value: searchValue,
        tabType: TAB_TYPE.FULLTEXT_SEARCH.id
      });
    } else {
      // setIsSearchFullText(false);
      // setIsFullTextSearch(false);
      handleChangeSearchRequest({ ...searchRequest, isNewSearch: true });
    }
  };
  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 }));
    }
  };


  if (!mounted) {
    return null;
  } 
  
  return (
    <div className={classes.homeContents + ` search-page`} id="homeContents">
      <SearchBoxForm tabs={searchTabs} handleChangeSearchValues={onSearch}/>
      {
        isMegreLayout &&
          <div style={{ minWidth: '200px', display: 'flex', justifyContent: 'flex-start', alignItems: 'center', marginLeft: below768 ? '10px' : '0px' }}>
            <SortSearchResult
              listSortField={listSorts}
              valueSort={sortOrder.sortField}
              isAsc={sortOrder.sort}
              onSort={onSortMegreLayout}
            />
          </div>
      }
      {/* content is not selectedContentGroup */}
      {
        !hideSearchResult && !selectedContentGroup.id && 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={[]}
              />
            );
          }
        })
      }

      {
        !hideSearchResult && 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}
                loadContentsNextPrevPage={handleLoadContentsNextPrevPage}
                selectHashtags={[]}
              />
            );
          }
        })
      }
    </div>
  );

}
