"use client"
import { useParams, useRouter } from "next/navigation";
import { AUTHEN_TYPES, BUTTON_ACTION, DISPLAY_SEARCH_RESULTS, DOMAIN_TYPE, LAYOUT_SETTING, OPTION_LOGIN, PAGING_POSITION, PAGING_TYPE, SEARCH_FIELD, SEO_SETTING_TYPE, SORT_FIELD_TYPE, TAB_TYPE, TABLE, TYPE_PRE_NEXT_PAGE, USER_CONFIG } from "@/lib/appConstant";
import { getCompanyDomain, getLayoutSettingAll, getLayoutViewPage, getSearchSetting, getSearchTabs, getServicePath, getTabSetting, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { ServiceViewSettings } from "@/types/serviceAdmin";
import { useTranslations } from "use-intl";
import { Fragment, useEffect, useState } from "react";
import * as _ from 'lodash';
import { useMounted } from "@/hooks/useMounted";
import useResponsive from "@/hooks/useResponsive";
import { makeStyles } from "tss-react/mui";
import { fetchContentSearch, fetchDataSearchFullText, fetchPublicContentSearch, getDataSearchPage, getFulltextSearch, getIdTabActive, getPaginationSearchPage, getSearchRequests, resetSearchPage, setIdTabSearch, setIsFullTextSearch, setOpenSearchFullScreen } from "@/lib/redux/features/search-page";
import { formatDate, getUserTrace, hashMD5 } from "@/lib/utils";
import StorageHelper from "@/lib/storeHelper";
import { STORAGE_KEYS } from "@/types/common";
import { Col, Row } from "antd";
import { TextField } from "@mui/material";
import SearchBoxForm from "../forms/tabs-search-box-form";
import CustomPagination from "../ui/custom-pagination";
import LoginModal from "../modal/login-modal";
import ModalConfirm from "../modal/modal-confirm";
import LoginForm from "../auth/form/login-form";
import SearchResult from "./search-result";
import SortSearchResult from "./sort-search-result";
import { getIsAuthenticated } from "@/lib/redux/features/auth";
import { addFavoriteContent, getShowFavorite, removeFavoriteContent, resetDownloadContentId, setCacheSearchRequest } from "@/lib/redux/features/content";
import { getAllSort, loadAllSort } from "@/lib/redux/features/sort";
import SwitchView from "../ui/switch/switch-view";

type PropsType = { viewSettings?: ServiceViewSettings };
type MakeStylesType = {
  tabSetting: any;
  below768: boolean;
};

const useStyle = makeStyles<MakeStylesType>()((theme, { below768, tabSetting }) => {
  return (
    {
      bold: {
        fontWeight: 700
      },
      searchPage: {
        border: 'none',
        backgroundColor: 'transparent',
        margin: 'auto'
      },
      searchTab: {
        padding: '16px',
        // margin: '0 -1rem 0rem -1rem',
        '& label': {
          fontWeight: 700
        },
        '& button': {
  
        }
      },
      navItem: {
        border: '1px solid #d0d0d0',
        flex: '1 0 0px',
        borderRadius: '5px 5px 0 0',
        marginLeft: 4,
        background: tabSetting.backgroundColorInactive || 'LightGray',
        borderColor: tabSetting.backgroundColorInactive || 'LightGray',
        fontWeight: 700,
        fontSize: tabSetting.fontSize || '1rem',
        textAlign: 'center',
        '&:first-of-type': {
          marginLeft: 0
        },
        '& .nav-link': {
          color: `${tabSetting.colorInactive || '#fff'}!important`
        }
      },
      activeNav: {
        border: 'none',
        background: tabSetting.backgroundColor || '#3d993a',
        '& .nav-link': {
          color: `${tabSetting.color || '#fff'}!important`
        }
      },
      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'
      },
      hasBox: {
        display: 'flex',
        flexDirection: 'column',
        pointerEvents: 'none',
        '& .MuiOutlinedInput-multiline': {
          borderRadius: 2
        },
        '& .MuiOutlinedInput-notchedOutline': {
          borderColor: '#767676'
        }
      },
      gridContainer: {
        '&.MuiGrid-grid-xs-6': {
          maxWidth: below768 ? '0px' : '50%',
          flexBasis: below768 ? '0px' : '50%'
        }
      },
      changeFilterConditions: {
        height: 32,
        display: 'flex',
        justifyContent: below768 ? 'space-between' : 'center',
        alignItems: 'center',
        border: '1px solid #585757',
        borderLeft: below768 ? 'none' : '',
        borderRight: below768 ? 'none' : '',
        borderRadius: below768 ? 0 : 16,
        overflow: 'hidden',
        padding: '0 12px',
        width: below768 ? '100%' : 'auto',
        maxWidth: '100%',
        cursor: 'pointer'
      }
    }
  );
});


const SearchPageRender = (props: any) => {

  const t = useTranslations("");
  const dispatch = useAppDispatch();
  const router = useRouter();
  const mounted = useMounted();
  const { below768 } = useResponsive();

  const servicePath = useAppSelector(getServicePath);
  const tabSetting = useAppSelector(getTabSetting);
  const viewSettings = useAppSelector(getViewSettings);
  const idTabActive = useAppSelector(getIdTabActive);
  const layoutSettingAll = useAppSelector(getLayoutSettingAll);
  const isFulltextSearch = useAppSelector((state) => state.searchPage.isFullTextSearch);
  const searchTabs = useAppSelector(getSearchTabs);



  const contents = useAppSelector(getDataSearchPage);
  const pagination = useAppSelector(getPaginationSearchPage);
  const searchSetting = useAppSelector(getSearchSetting);
  const isLoggedIn = useAppSelector(getIsAuthenticated);
  const domain = useAppSelector(getCompanyDomain);
  const showFavorite = useAppSelector(getShowFavorite);
  const listSortField = useAppSelector(getAllSort);
  const layoutViewPage = useAppSelector(getLayoutViewPage);
  const searchRequestsStore = useAppSelector(getSearchRequests);
  const fulltextSearchStore = useAppSelector(getFulltextSearch);


  const [showLoginFormModal, setShowLoginFormModal] = useState(false);
  const [url, setUrl] = useState('');
  const [isShowViewBook, setIsShowViewBook] = useState(false);
  const [searchRequest, setSearchRequest] = useState<any[]>([]);
  const [contentDeatilId, setContentDeatilId] = useState('');
  const [valueSort, setValueSort] = useState<any>(null);
  const [isAsc, setSort] = useState(false);
  const [showConfirmViewer, setShowConfirmViewer] = useState(false);
  const [fulltextSearch, setFulltextSearch] = useState<any>();
  const [isSearchFullText, setIsSearchFullText] = useState(false);
  const [isListView, setIsListView] = useState(false);
  const [activeTab, setActiveTab] = useState('1');

  const { contentId } = useParams();
  const styleButtonSearch = tabSetting.buttons ? tabSetting.buttons.filter(item => item.actionType === BUTTON_ACTION.SEARCH.id)[0] : {};

  const isOpenType = viewSettings.accountType === OPTION_LOGIN.OPEN_TYPE;
  const isFullDomain = viewSettings.domainType === DOMAIN_TYPE.FULL_DOMAIN;
  const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
  const isSearchLayout = layoutViewPage === LAYOUT_SETTING.SEARCH_LAYOUT.id;

  const cacheParams = StorageHelper.getSessionObject(STORAGE_KEYS.cacheStorage);
  const cacheContentId = cacheParams ? cacheParams.contentId : '';
  const isScrollPage = searchSetting.searchResultPagingType === PAGING_TYPE.SCROLL && layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;

  const { classes } = useStyle({ below768, tabSetting });

  useEffect(() => {
    if (!searchRequest) {
      dispatch(resetSearchPage());
    } else {
      dispatch(setCacheSearchRequest({ searchRequest: searchRequest }));
    }
  }, [searchRequest]);

  useEffect(() => {
    const protocol = window.location.protocol;
    const hash = window.location.hash !== '' ? '#' : '';
    const port = window.location.port;
    const path = isFullDomain
      ? ''
      : '/' + servicePath;
    if (port) {
      setUrl(protocol + '//' + domain + ':' + port + path + hash);
    } else {
      setUrl(protocol + '//' + domain + path + hash);
    }
    dispatch(loadAllSort({ type: SORT_FIELD_TYPE.SORT_FIELD_SEARCH, domain: domain, path: servicePath }));
    // dispatch(loadPublicContentGroups());
  }, []);

  // useEffect(() => {
  //   // queriesSearch
  //   if (tabs.length > 0) {
  //     setActiveTab(tabs[0].id);
  //   }
  // }, [tabs]);

  useEffect(() => {
    if (idTabActive || idTabActive === 0) {
      setActiveTab(idTabActive);
    }
  }, [idTabActive]);

  useEffect(() => {
    if (isLoggedIn && contentDeatilId) {
      if (isShowViewBook) {
        const urlViewer = url + '/view-online/' + contentDeatilId;
        const windowReference = window.open(urlViewer);
        if (!windowReference) {
          setShowConfirmViewer(true);
        }
        setIsShowViewBook(false);
      } else {
        dispatch(resetSearchPage());
        reloadLogin();
      }
    } else {
      setIsShowViewBook(false);
    }
  }, [isLoggedIn]);

  useEffect(() => {
    if (isLoggedIn && cacheParams) {
      if (cacheParams.activeTab && cacheParams.searchRequest) {
        setActiveTab(cacheParams.activeTab);
        setSearchRequest(cacheParams.searchRequest);
        const payload = {
          path: servicePath,
          searchRequests: cacheParams.searchRequest,
          pagination: {
            page: TABLE.DEFAULT_PAGE_NUMBER,
            size: TABLE.DEFAULT_PAGE_SIZE,
            sort: isAsc,
            sort_by: valueSort
          }
        };
        handleSearchContent(payload);
      }
      if (cacheParams.isShowViewBook && cacheParams.contentId && url) {
        const urlViewer = url + '/view-online/' + cacheParams.contentId;
        const windowReference = window.open(urlViewer);
        if (!windowReference) {
          setShowConfirmViewer(true);
        }
        setIsShowViewBook(false);
      } else {
        dispatch(resetSearchPage());
        reloadLogin();
      }
    } else {
      setIsShowViewBook(false);
    }
  }, [isLoggedIn, url]);

  useEffect(() => {
    if (searchSetting && searchSetting.displaySearchResults === DISPLAY_SEARCH_RESULTS.LIST_VIEW) {
      setIsListView(true);
    }
    if (searchSetting && searchSetting.displaySearchResults === DISPLAY_SEARCH_RESULTS.TITLE_VIEW) {
      setIsListView(false);
    }
  }, [searchSetting]);

  useEffect(() => {
    if (searchRequestsStore) {
      setSearchRequest(searchRequestsStore);
    }
  }, [searchRequestsStore]);

  useEffect(() => {
    if (fulltextSearchStore) {
      setFulltextSearch(fulltextSearchStore);
    }
  }, [fulltextSearchStore]);

  useEffect(() => {
    setIsSearchFullText(isFulltextSearch);
  }, [isFulltextSearch]);

  const handleChangeFavoriteContent = (contentId, isFavorite, contentGroupId) => {
    const params = {
      contentGroupId: contentGroupId
    };
    if (isFavorite) {
      dispatch(removeFavoriteContent({ contentId: contentId, contentGroup: params }));
    } else {
      dispatch(addFavoriteContent({ contentId: contentId, contentGroup: params }));
    }
  };


  const toggle = tab => {
    if (activeTab !== tab) setActiveTab(tab);
  };
  const handleChangeTab = (tab) => {
    toggle(tab.id);
    if (tab.type === TAB_TYPE.FULLTEXT_SEARCH.id) {
      setIsSearchFullText(true);
      dispatch(setIsFullTextSearch(true));
    } else {
      setIsSearchFullText(false);
      dispatch(setIsFullTextSearch(false));
    }
  };
  const handleSearchContent = queries => {
    if (isLoggedIn) {
      if (isSearchFullText) {
        dispatch(fetchDataSearchFullText({
          searchKey: fulltextSearch,
          pagination: queries.pagination,
          isScrollPage: queries.isScrollPage
        }));
      } else {
        dispatch(fetchContentSearch(queries));
      }
    } else {
      if (isSearchFullText) {
        dispatch(fetchDataSearchFullText({
          searchKey: fulltextSearch,
          pagination: queries.pagination,
          isScrollPage: queries.isScrollPage
        }));
      } else {
        if (!queries.searchRequests) {
          dispatch(fetchPublicContentSearch({
            ...queries,
            searchRequests: []
          }));
        } else {
          dispatch(fetchPublicContentSearch(queries));
        }
      }
    }
  };

  const showContentDetail = ({ contentId, contentGroupId }) => {
    // setShowContentDetailDialog(true);
    dispatch(resetDownloadContentId());
    if (contentGroupId) {
      router.push(`${servicePath ? '/'+servicePath : ''}/${contentGroupId}/${contentId}`);
    } else {
      router.push(`${servicePath ? '/'+servicePath : ''}/search/${contentId}`);
    }
  };

  const onChangePage = (pageNumber) => {
    const params = { ...pagination };
    params.page = pageNumber;
    if (valueSort) {
      params.sort_by = valueSort;
    }
    params.sort = isAsc;
    const request = {
      path: servicePath,
      searchRequests: searchRequestsStore.length > 0 ? searchRequestsStore : searchRequest,
      pagination: {
        ...params
      },
      isScrollPage
    };
    handleSearchContent(request);
  };

  const onSort = (sort: string, asc: boolean) => {
    setValueSort(sort);
    setSort(asc);
    const params = { ...pagination };
    params.sort_by = sort;
    params.sort = asc;

    params.page = 1;
    params.size = TABLE.DEFAULT_PAGE_SIZE;
    handleSearchContent({
      path: servicePath,
      searchRequests: searchRequest.length > 0 ? searchRequest : searchRequestsStore,
      pagination: params
    });
  };

  const renderContentInfo = (itemSetting, contentInfo, isFullWidth) => {
    switch (itemSetting.field) {
      case SEARCH_FIELD.TITLE.id:
        return returnTemplateContentInfo(SEARCH_FIELD.TITLE, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.AUTHOR.id:
        return returnTemplateContentInfo(SEARCH_FIELD.AUTHOR, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.KEYWORDS.id:
        return returnTemplateContentInfo(SEARCH_FIELD.KEYWORDS, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.TOC.id:
        return returnTemplateContentInfo(SEARCH_FIELD.TOC, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.DISTRIBUTOR.id:
        return returnTemplateContentInfo(SEARCH_FIELD.DISTRIBUTOR, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.DESCRIPTION.id:
        return returnTemplateContentInfo(SEARCH_FIELD.DESCRIPTION, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.PARAM_1.id:
        return returnTemplateContentInfo(SEARCH_FIELD.PARAM_1, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.PARAM_2.id:
        return returnTemplateContentInfo(SEARCH_FIELD.PARAM_2, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.PARAM_3.id:
        return returnTemplateContentInfo(SEARCH_FIELD.PARAM_3, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.PARAM_4.id:
        return returnTemplateContentInfo(SEARCH_FIELD.PARAM_4, itemSetting, contentInfo, isFullWidth);
      case SEARCH_FIELD.PARAM_5.id:
        return returnTemplateContentInfo(SEARCH_FIELD.PARAM_5, itemSetting, contentInfo, isFullWidth);
      default:
        break;
    }
  };

  const handleSetInnerHTML = (text) => {
    return (<span dangerouslySetInnerHTML={{ __html: text }} />);
  };

  const returnTemplateContentInfo = (searchField, itemSetting, contentInfo, isFullWidth) => {
    return (
      <Col
        sm={isFullWidth ? 24 : Number(itemSetting.size) * 2}
        key={`key-detail-${searchField.dbKey}-${(new Date()).getTime()}`}
        id={`key-detail-${searchField.dbKey}-${(new Date()).getTime()}`}
        className={`mB-1 ${itemSetting.hasBox && 'has-box'}`}
      >
        {
          itemSetting.isShowLabel && isMegreLayout
            ? <span >
              {`${itemSetting.title}: `}
            </span>
            : <></>
        }
        {
          !isMegreLayout && <span >
            {`${itemSetting.title}: `}
          </span>
        }
        {
          itemSetting.hasBox
            ? <TextField variant={'outlined'} multiline type={'textarea'} value={contentInfo[searchField.dbKey]} />
            : handleSetInnerHTML(contentInfo[searchField.dbKey])
        }
      </Col>
    );
  };

  const onSearch = (form: any) => {
    const pagination = {
      page: TABLE.DEFAULT_PAGE_NUMBER,
      size: TABLE.DEFAULT_PAGE_SIZE,
      sort: isAsc,
      sort_by: valueSort
    };
    if (form.tabType === TAB_TYPE.FULLTEXT_SEARCH.id) {
      setFulltextSearch(form.value);
      dispatch(setIsFullTextSearch(true));
      setIsSearchFullText(true);
      dispatch(fetchDataSearchFullText({
        searchKey: form.value,
        pagination,
        isNewSearch: true,
        isScrollPage
      }));
    } else {
      setFulltextSearch(null);
      dispatch(setIsFullTextSearch(false));
      setIsSearchFullText(false);
      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;
          }
          searchRequests = [...searchRequests, param];
        }
      }
      setSearchRequest(searchRequests);
      dispatch(setCacheSearchRequest({ searchRequest: searchRequests }));
      const payload = {
        path: servicePath,
        searchRequests: searchRequests,
        pagination: {
          page: TABLE.DEFAULT_PAGE_NUMBER,
          size: TABLE.DEFAULT_PAGE_SIZE,
          // size: form.isSearchSpecialContentsGroup ? 9999 : TABLE.DEFAULT_PAGE_SIZE,
          sort: isAsc,
          sort_by: valueSort
        },
        isNewSearch: true,
        isScrollPage
      };
      handleSearchContent(payload);
    }
  };

  const reloadLogin = () => {
    const payload = {
      path: servicePath,
      searchRequests: searchRequest,
      pagination: {
        ...pagination,
        sort: isAsc,
        sort_by: valueSort
      }
    };
    handleSearchContent(payload);
  };

  const showViewBook = (content: any) => {
    setIsShowViewBook(true);
    if (isLoggedIn || isOpenType) {
      if (cacheParams) {
        StorageHelper.removeSessionItem(STORAGE_KEYS.cacheStorage);
      }
      const urlViewer = url + '/view-online/' + (content.id || contentDeatilId);
      window.open(urlViewer, '_blank');
    } else {
      setContentDeatilId(content.id);
      setShowLoginFormModal(true);
    }
  };

  const cancelLoginModal = () => {
    setShowLoginFormModal(false);
    setIsShowViewBook(false);
  };
  const handleChangeSearchValues = (searchRequest, tab, isSearchSpecialContentsGroup) => {
    dispatch(setIdTabSearch(tab.id));
    // setSpecialContentsGroupId(null);
    if (tab.type === TAB_TYPE.FULLTEXT_SEARCH.id) {
      dispatch(setIsFullTextSearch(true));
      setIsSearchFullText(true);
      let searchValue;
      for (const key in searchRequest) {
        searchValue = searchRequest[key];
      }
      onSearch({
        value: searchValue,
        tabType: TAB_TYPE.FULLTEXT_SEARCH.id
      });
    } else {
      dispatch(setIsFullTextSearch(false));
      setIsSearchFullText(false);
      onSearch({ ...searchRequest, isSearchSpecialContentsGroup });
    }
  };

  const handleCancelViewBook = () => {
    if (cacheParams) {
      StorageHelper.removeSessionItem(STORAGE_KEYS.cacheStorage);
    }
    setShowConfirmViewer(false);
  };

  return (
    <div className={`card search-page ${classes.searchPage}`}>
      <Fragment>
        {
          (isSearchLayout || (isMegreLayout && !layoutSettingAll.isFullScreenSearch)) &&
          <div className={`${classes.searchTab}`}>
            <SearchBoxForm tabs={searchTabs} handleChangeSearchValues={handleChangeSearchValues}/>
            {/* <Nav tabs pills style={{ borderBottom: 0 }}>
              {tabs.length > 0 && tabs.map((tab: any, index: number) => {
                return (
                  <NavItem onClick={() => { toggle(tab.id) }} style={{ cursor: 'pointer', margin: `5px ${index + 1 === tabs.length ? 0 : 3}px 0 0` }} className={`${classes.navItem} ${activeTab === tab.id && classes.activeNav}`} key={`nav-${tab.id}`}>
                    <NavLink
                      className={`${classes.navlink}`}
                      onClick={() => handleChangeTab(tab)}
                      active={activeTab === tab.id}
                      style={{ cursor: 'pointer' }}
                    >
                      {tab.title}
                    </NavLink>
                  </NavItem>
                );
              })}
            </Nav>
            <TabContent className={classes.tabContent} activeTab={activeTab}>
              {
                tabs.length > 0 && tabs.map(tab => {
                  return (
                    <TabPane tabId={tab.id} key={`pane-${tab.id}`}>
                      <SearchBox
                        isLoggedIn={isLoggedIn}
                        activeTab={activeTab}
                        tabId={tab.id}
                        searchBoxs={tab.searchBoxes}
                        onSubmit={(searchValues, isSearchSpecialContentsGroup) => handleChangeSearchValues(searchValues, tab, isSearchSpecialContentsGroup)}
                        // onSearchSpecialContentsGroup={(contentGroupId) => onSearchSpecialContentsGroup(contentGroupId, tab)}
                        styleButtonSearch={styleButtonSearch}
                        searchRequest={searchRequest}
                      />
                    </TabPane>
                  );
                })
              }
            </TabContent> */}
          </div>
        }
        <Row gutter={16} align="middle" justify="space-between" style={{ marginBottom: 20 }} className={classes.gridContainer}>
          
          <Col xs={isMegreLayout ? 12 : 24} style={{ padding: '0 16px' }}>
            <p style={{ marginLeft: '0.5rem' }}>{t('label.searchResults')}</p>
            <p style={{ marginLeft: '0.5rem' }}>{t('label.numberItemSearch', { number: pagination.totalRecords || 0 })}</p>
          </Col>
          {
            isMegreLayout && layoutSettingAll.isFullScreenSearch &&
            <Col xs={below768 ? 24 : 12} className="text-right">
              <div
                className={`text-right ${classes.changeFilterConditions}`}
                onClick={() => dispatch(setOpenSearchFullScreen(true))}
                style={{
                  width: below768 ? '100%' : 'fit-content',
                  float: below768 ? undefined : 'right',
                  whiteSpace: 'nowrap'
                }}
              >
                <span style={{ float: below768 ? 'left' : undefined, margin: '0 15px 0 5px' }}>
                  {t('label.changeFilterConditions')}
                </span>
                <i style={{ float: below768 ? 'right' : undefined, fontSize: 19 }} className="fa fa-angle-right" aria-hidden="true"/>
              </div>
            </Col>
          }
          {/* {
            isMegreLayout && */}
          <Col sm={isMegreLayout ? 12 : 24} style={{ justifyContent: isMegreLayout && layoutSettingAll.isFullScreenSearch ? 'left' : 'right', display: 'flex', alignItems: 'center', padding: isMegreLayout && !layoutSettingAll.isFullScreenSearch ? '0 1rem 0 0' : 0 }}>
            <SortSearchResult
              data={searchSetting.sortedContentFields}
              listSortField={listSortField}
              valueSort={valueSort}
              isAsc={isAsc}
              onSort={onSort}
              isDisabledCreatedDate={true}
              disabled={!contents || contents.length === 0 || !searchRequest}
            />
          </Col>
          {/* } */}
          <Col sm={isMegreLayout && layoutSettingAll.isFullScreenSearch ? 12 : 24} style={{ textAlign: 'right', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: 0, marginBottom: below768 ? '10px' : '0px' }}>
            {
              isMegreLayout && searchSetting && searchSetting.displaySearchResults === DISPLAY_SEARCH_RESULTS.ALL &&
              <SwitchView
                checked={isListView}
                onChange={(checked: boolean) => {
                  setIsListView(checked);
                }}
              />
            }
          </Col>
        </Row>
        {
          (searchSetting.searchResultPagingType === PAGING_TYPE.NUMBER_PAGING || layoutViewPage === LAYOUT_SETTING.SEARCH_LAYOUT.id) &&
          (searchSetting.pagingPosition === PAGING_POSITION.TOP.id || searchSetting.pagingPosition === PAGING_POSITION.TOP_AND_BOTTOM.id) &&
          <CustomPagination
            valueSort={valueSort}
            isAsc={isAsc}
            page={pagination.page}
            totalPages={pagination.totalPages}
            onChangePage={onChangePage}
          />
        }
        <SearchResult
          data={contents}
          isMegreLayout={isMegreLayout}
          isLoggedIn={isLoggedIn}
          contentSetting={searchSetting.contentSearchResults}
          displaySetting={searchSetting.displaySearchResults}
          pagingType={searchSetting.searchResultPagingType}
          pagination={pagination}
          showContentDetail={showContentDetail}
          renderContentInfo={renderContentInfo}
          openViewOnline={showViewBook}
          onSelectFavorite={handleChangeFavoriteContent}
          onChangePage={onChangePage}
          showFavorite={showFavorite}
          isListView={isListView}
        />
        {
          (searchSetting.searchResultPagingType === PAGING_TYPE.NUMBER_PAGING || layoutViewPage === LAYOUT_SETTING.SEARCH_LAYOUT.id) &&
          (searchSetting.pagingPosition === PAGING_POSITION.BOTTOM.id ||
            searchSetting.pagingPosition === PAGING_POSITION.TOP_AND_BOTTOM.id)
            ? <CustomPagination
              valueSort={valueSort}
              isAsc={isAsc}
              page={pagination.page}
              totalPages={pagination.totalPages}
              onChangePage={onChangePage}
            />
            : null
        }
      </Fragment>
      <LoginModal
          isOpen={showLoginFormModal}
          toggle={() => cancelLoginModal()}
          size="middle"
          className="mx-4 my-4"
        >
          <div className="mx-4 my-4 pl-5 pr-5">
            <LoginForm notChangeRouter={true} handleSuccess={() => {
              window && window.location.reload();
              cancelLoginModal()
            }}/>
          </div>
        </LoginModal>
      <ModalConfirm
        isOpen={showConfirmViewer}
        toggle={() => handleCancelViewBook()}
        message={t('label.confirmViewNewTab')}
        doConfirm={() => showViewBook({ id: cacheContentId || contentDeatilId })}
        doCancel={() => handleCancelViewBook()}
        backdrop={'static'}
        level={'info'}
      />
    </div>
  );
};




export default SearchPageRender;
