"use client";

import React from "react";
import { usePathname } from "@/i18n/routing";
import { useBreakpoint } from "@/hooks/useBreakpoint";
import { useTranslations } from "next-intl";
import { makeStyles } from 'tss-react/mui';
import { CONTENT_GROUP_TYPE, DOMAIN_TYPE, OPTION_LOGIN } from "@/lib/appConstant";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { getHeaderSetting, getLayoutSettingAll, getServicePath, getSidebarSetting, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import useResponsive from "@/hooks/useResponsive";
import { clearAuthInfo, doLogout, getAuthInfo, getIsMobileApp } from "@/lib/redux/features/auth";
import { ResponseStatus, STORAGE_KEYS } from "@/types/common";
import { LogoutResponse } from "@/types/auth";
import StorageHelper from "@/lib/storeHelper";
import { getPublicContentGroups } from "@/lib/redux/features/content";
import { ContentGroupMapRender } from "@/types/content-group";
import { Layout } from "antd";
import Box from "@mui/material/Box";
import Drawer from "@mui/material/Drawer";
import { BookOpenText, CircleUserRound, GalleryVerticalEnd, LogIn, LogOut, UserPlus } from "lucide-react";
import { useMounted } from "@/hooks/useMounted";
import { SortEntity } from "@/types/sort";
import HomeSort from "./home/home-sort";
import { ServiceViewSettings } from "@/types/serviceAdmin";
import { getOpenSidebar, onToggleSidebar } from "@/lib/redux/features/layout"; 
import { useRouter } from "next/navigation";
import CaretDownOutlined from "@ant-design/icons/CaretDownOutlined";
import CaretUpOutlined from "@ant-design/icons/CaretUpOutlined";

const { Sider } = Layout;
// use params
const contentGroupId = null;
const contentId = null;

type PropsType = {
  listSorts?: SortEntity[];
  viewSettings: ServiceViewSettings

  sort?: any;
  changeSort?: any;
  pageSize?: number;
  newInformation?: any;
  isDisableSort?: boolean;
  handleLoadContent?: any;
  showContentDetail?: any;
  // onSelectContentGroup?: any;
}

type MakeStylesType = {
  background: any;
  below768: boolean;
  text: any;
  barBackground: any;
  barText: any;
  active: any;
  textActive: any;
  styleHeader: any;
};
const useStyles = makeStyles<MakeStylesType>()((theme, { below768, background, text, barBackground, barText, active, textActive, styleHeader }) => {
  return (
    {
      sideBar: {
        minWidth: 200,
        width: below768 ? '66vw' : 200,
        // color: text || '#707070',
        // fontWeight: 700,
        display: 'flex',
        flexDirection: 'column',
        background: background || '#fff',
        zIndex: 100
        // fontSize: below768 ? '12px' : '16px'
      },
      customCSS: {
        color: text || '#707070',
        fontWeight: 700,
        fontSize: below768 ? '12px' : '16px'
      },
      sideBarmobile: {
        minWidth: 200,
        width: '66vw',
        // height: 'calc(100vh - 80px)',
        height: 'calc(var(--vh, 1vh) * 100) -80',
        inset: '80px 0px 0px 0px!important',
        paddingBottom: 40,
        '& .MuiBackdrop-root': {
          height: 'calc(100vh - 80px)',
          top: '80px'
        }
      },
      groupSort: {
        background: barBackground || '#e2e2e2',
        color: barText || '#707070',
        padding: '0.5rem 1rem',
        width: '100%',
        border: '1px solid #fff'
      },
      newInformation: {
        background: barBackground || '#e2e2e2',
        color: barText || '#707070',
        padding: '0.5rem 1rem',
        width: '100%',
        border: '1px solid #fff'
      },
      sortOrder: {
        display: 'flex',
        flexFlow: 'row',
        width: '100%',
        cursor: 'pointer',
        height: 'fit-content',
        minHeight: 36,
        '& div': {
          padding: '0.5rem 1rem',
          flex: '1 0 0px',
          display: 'flex',
          flexFlow: 'row wrap',
          wordBreak: 'break-word',
          wordWrap: 'break-word'
        },
        '& .disabled': {
          cursor: 'default',
          color: '#cfccd6'
        },
        '& div:first-of-type': {
          borderRight: '1px solid #e2e2e2'
        },
        '& div:hover': {
          ['@media (min-width:619px)']: { // eslint-disable-line no-useless-computed-key
            background: active || '#1aa758',
            color: textActive || '#fff'
          }
        },
        '& div.disabled:hover': {
          ['@media (min-width:619px)']: { // eslint-disable-line no-useless-computed-key
            background: 'none',
            color: '#cfccd6'
          }
        }
      },
      sortGenres: {
        display: 'flex',
        flexDirection: 'column',
        width: '100%'
      },
      sortItem: {
        padding: '0.5rem 1rem',
        cursor: 'pointer',
        wordBreak: 'break-word',
        wordWrap: 'break-word'
      },
      sortItemWrapper: {
        borderBottom: '1px solid #e2e2e2',
        '&:hover': {
          ['@media (min-width:619px)']: { // eslint-disable-line no-useless-computed-key
            background: active || '#1aa758',
            color: textActive || '#fff'
          }
        }
      },
      iconOpen: {
        transform: 'rotate(180deg)'
      },
      hideSidebar: {
        transform: 'translateX(-500px)',
        transition: 'transform .3s ease-in-out',
        width: 0,
        minWidth: 'unset',
        position: 'fixed'
      },
      selected: {
        background: active || '#1aa758',
        color: textActive || '#fff'
      },
      disabled: {
        opacity: 0.6,
        pointerEvents: 'none'
      },
      sortSelectbox: {
        paddingRight: '1rem'
      },
      headerItem: {
        color: styleHeader.color || '#d0d0d0',
        cursor: 'pointer',
      },
      sortIcon: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      },
      textInfo: {
        // '& p:has(em)': {
        //   transform: 'skewX(-8deg)'
        // },
        // '& span:has(em)': {
        //   transform: 'skewX(-8deg)'
        // }
        // '& em': {
        //   color: '',
        //   fontWeight: '',
        //   fontSize: '',
        //   fontStyle: ''
        // }
      }
    }
  );
});
const AppSidebar = (props: PropsType) => {
  const {
    // onSelectContentGroup = () => {},
    sort = {},
    changeSort = () => {},
    pageSize,
    isDisableSort,
    listSorts = [],
    handleLoadContent = () => {},
    newInformation,
    showContentDetail,
  } = props;

  const router = useRouter();
  const dispatch = useAppDispatch();
  const pathname = usePathname();
  const locale = pathname.split("/")[1];
  const t = useTranslations("");
  const authInfo = useAppSelector(getAuthInfo);
  const mounted = useMounted();
  

  const { below768, getBelow768 } = useResponsive();

  // const { contentGroupId, contentId } = useParams();
  const sidebarSetting = useAppSelector(getSidebarSetting);
  const styleHeader = useAppSelector(getHeaderSetting);
  const viewSettings = useAppSelector(getViewSettings);
  const servicePath = useAppSelector(getServicePath);
  const isOpenSidebar = useAppSelector(getOpenSidebar);
  const layoutSettingAll = useAppSelector(getLayoutSettingAll);
  const isMobileApp = useAppSelector(getIsMobileApp);
  const contentGroups = useAppSelector(getPublicContentGroups) as ContentGroupMapRender[] || [] as ContentGroupMapRender[];

  const isOpenType = viewSettings.accountType === OPTION_LOGIN.OPEN_TYPE;

  const showSidebarDetail = viewSettings.contentSearchResultSettingResponse?.showSidebar && showContentDetail;
  
  const showSidebar = layoutSettingAll.showSidebar || showSidebarDetail;
  const { background, active, text, textActive, barBackground, barText } = sidebarSetting;
  const isHomeSearchPage = mounted && window.location.pathname.includes('home-search');
  const isFullDomain = viewSettings.domainType === DOMAIN_TYPE.FULL_DOMAIN;
  const redirectUrl = mounted ? (isFullDomain ? `${window.location.origin}/login` : `${window.location.origin}/${servicePath}/login`) : '';


  const { classes } = useStyles({ below768, background, text, barBackground, barText, active, textActive, styleHeader });

  const specialContentGroup = contentGroups.filter(item => item.type !== CONTENT_GROUP_TYPE.NORMAL);
  const normalContentGroup = contentGroups.filter(item => item.type === CONTENT_GROUP_TYPE.NORMAL);

  const onSort = (sort: number, asc: boolean) => {
    const params = { sortField: sort, sort: asc };
    changeSort(params);
  };

  const onSelectContentGroup = (contentGroupId, isBackHome) => {
    
    if (isBackHome) {
      router.push(`${servicePath ? '/'+servicePath : ''}/`);
    } else {
      router.push(`${servicePath ? '/'+servicePath : ''}/${contentGroupId}`);
    }
    // const cache = searchRequest;
    // setCacheSearchRequest({ searchRequest: cache });
  };
  
  const registerGakkenUser = async () => {
    const gakkenUrl = `${process.env.NEXT_PUBLIC_GAKKEN_LINK}/user-register-1?response_type=code&client_id=${viewSettings.gakkenServiceCode}&redirect_uri=${redirectUrl}`;
    window.location.replace(gakkenUrl);
  };

  const handleLogout = async () => {
    const result = await dispatch(doLogout());
    const payload = result?.payload as LogoutResponse;
    if (payload && payload.status === ResponseStatus.SUCCESS) {
      dispatch(clearAuthInfo());
      // dispatch(clearUserDetail());
      StorageHelper.removeLocalItem(STORAGE_KEYS.user);
      router.push(`${servicePath ? '/'+servicePath : ''}/login`);
    }
  };

  const renderInformation = () => {
    let newFormat;
    // eslint-disable-next-line no-unused-vars
    if (newInformation.includes('<ul>')) {
      newFormat = newInformation.replaceAll('<ul>', '<ul style="margin: 0; padding: 0px 0px 0px 20px">').replaceAll('&nbsp;', '').replaceAll('<li></li>', '');

      if (newFormat.includes('</li>')) {
        return (
          <React.Fragment>
            <div className={`${classes.newInformation} ${classes.customCSS}`}>
            {t('title.newInformation')}
            </div>
            <div className={classes.textInfo} style={{ padding: '5px 5px 5px 7px' }}>
              <div className={classes.textInfo} style={{ wordBreak: 'break-word' }} dangerouslySetInnerHTML={{ __html: newFormat }} />
            </div>
          </React.Fragment>
        );
      } else {
        return (
          <></>
        );
      }
    } else {
      // if (newInformation.includes('<p></p>')) {
      //   newFormat = newInformation.trim().replaceAll('&nbsp;', '').replaceAll('<p></p>', '').split('\n');
      // } else {
      newFormat = newInformation.trim().replaceAll('&nbsp;', '').replaceAll('<p></p>', '').split('\n');
      // }
      const isNewFormat = newFormat.filter(item => item !== '');
      if (isNewFormat.length === 0) {
        return (
          <></>
        );
      } else {
        return (
          <React.Fragment>
            <div className={`${classes.newInformation} ${classes.customCSS}`}>
              {t('title.newInformation')}
            </div>
            <div style={{ padding: '5px 5px 5px 7px' }}>
              <ul>
                {newFormat.map((item, index) => (
                  item && item !== '' && <li key={index} className={classes.textInfo}>
                    <div className={classes.textInfo} style={{ wordBreak: 'break-word' }} dangerouslySetInnerHTML={{ __html: item }} />
                  </li>
                ))}
              </ul>
            </div>
          </React.Fragment>
        );
      }
    }
  };

  const SidebarContentRender = () => (
    <React.Fragment>
      {
        listSorts.length > 0 &&
        <React.Fragment>
          <div className={`${classes.groupSort} ${classes.customCSS}`}>
            {t('title.sortOrder')}
          </div>
          {
            listSorts.length > 2
              ? <div className={`${classes.sortSelectbox} ${isDisableSort && classes.disabled} ${classes.customCSS}`}>
                <HomeSort
                  listSortField={listSorts}
                  valueSort={sort.sortField}
                  isAsc={sort.sort}
                  onSort={onSort}
                  disabled={isDisableSort}
                />
              </div>
              : <div className={`${classes.sortOrder} ${isDisableSort && classes.disabled} ${classes.customCSS}`}>
                {
                  listSorts.map((sortItem, index) => {
                    const isDisabled = (isHomeSearchPage && sortItem.field === 12);
                    return (
                      <div key={`sort-item-${index}`} onClick={() => !isDisabled && onSort(sortItem.field, sort.sortField === sortItem.field ? !sort.sort : sortItem.isAcsDefault)} className={`${sort.sortField === sortItem.field && classes.selected} ${isDisabled ? 'disabled' : ''}`}>
                        <span>{sortItem.title}</span>
                        {
                          sort.sortField === sortItem.field && sort.sort === false && (
                            <CaretDownOutlined className={`ml-1 ${classes.sortIcon}`}/>
                          )
                        }
                        {
                          sort.sortField === sortItem.field && sort.sort === true && (
                            <CaretUpOutlined className={` ml-1 ${classes.sortIcon}`}/>
                          )
                        }
                      </div>
                    );
                  })
                }
              </div>
          }
        </React.Fragment>
      }
      {
        specialContentGroup && specialContentGroup.map(item => (
          <div
            key={`special-group-${item.id}`}
            className={`${classes.groupSort} ${classes.sortItem} ${`${contentGroupId}` === `${item.id}` && !contentId ? classes.selected : ''} ${classes.customCSS}`}
            onClick={() => {
              onSelectContentGroup(item.id, `${contentGroupId}` === `${item.id}` && !contentId);
              const pageNum = item.page ? item.page : 1;
              const numItems = contentGroupId
                ? pageSize
                : item.isWrapLine ? item.itemSize : item.numRow * item.itemSize;
              handleLoadContent(item, pageNum, numItems);
            }}
          >
            {item.name}
          </div>
        ))
      }
      <div className={`${classes.groupSort} ${classes.customCSS}`}>
        {t('title.differentGenres')}
      </div>
      <div className={classes.sortGenres}>
        {
          normalContentGroup.map(item => {
            return (
              <div
                key={`cg-${item.id}`}
                className={`${classes.sortItemWrapper} ${`${contentGroupId}` === `${item.id}` && !contentId && classes.selected} ${classes.customCSS}`}
                onClick={() => onSelectContentGroup(item.id, `${contentGroupId}` === `${item.id}` && !contentId)}
              >
                <div className={classes.sortItem}>
                  {item.name}
                </div>
              </div>
            );
          })
        }
      </div>
      {newInformation && renderInformation()}
    </React.Fragment>

  );
  
  
  const toggleSidebar = () => {
    dispatch(onToggleSidebar());
  };
  
  return (
    <>
      {
        below768 && showSidebar &&
        <Drawer
          anchor="left"
          open={isOpenSidebar}
          classes={{
            root: classes.sideBarmobile,
            paper: classes.sideBarmobile
          }}
          onClose={() => toggleSidebar()}
          ModalProps={{
            keepMounted: true // Better open performance on mobile.
          }}
        >
          <Box display="flex" padding={'16px 6px'} role="presentation" minWidth={200} justifyContent="space-around">
            <Box className={classes.headerItem}>
              <BookOpenText onClick={() => router.push(`${servicePath ? '/'+servicePath : ''}/home-search`)} />
            </Box>
            {
              !isOpenType && !!authInfo &&
              <React.Fragment>
                {
                  authInfo.roleLevel !== 4 && !isMobileApp && <Box className={classes.headerItem}>
                    <CircleUserRound className="mr-2" onClick={() => router.push(`${servicePath ? '/'+servicePath : ''}/profile`)} />
                  </Box>
                }
                {
                  !isMobileApp &&
                  <Box className={classes.headerItem}>
                    <GalleryVerticalEnd onClick={() => router.push(`${servicePath ? '/'+servicePath : ''}/subscription`)} />
                  </Box>
                }
                {
                  !isMobileApp &&
                  <Box className={classes.headerItem}>
                    <LogOut onClick={() => { handleLogout() }} />
                  </Box>
                }
              </React.Fragment>
            }
            {
              !isOpenType && !authInfo &&
              <>
                <Box className={classes.headerItem}>
                  {
                    viewSettings.accountType === OPTION_LOGIN.GAKKEN_ID && viewSettings.isAutoRegisterGakkenAccountAtLogin &&
                    <div
                      className={classes.headerItem}
                      onClick={() => registerGakkenUser()}
                    >
                      <UserPlus className="mr-2"/>
                    </div>
                  }
                  {
                    viewSettings.accountType !== OPTION_LOGIN.GAKKEN_ID && viewSettings.accountType !== OPTION_LOGIN.OPEN_TYPE && viewSettings.isShowLinkRegisterUser &&
                    <div className={classes.headerItem} onClick={() => router.push(`${servicePath ? '/'+servicePath : ''}/register`)}>
                      <UserPlus className="mr-2"/>
                    </div>
                  }
                </Box>
                <Box className={classes.headerItem}>
                  <LogIn onClick={() => {
                    // setShowLoginFormModal(true);
                    // setIsOpenSidebar(false);
                  }} />
                </Box>
              </>
            }
          </Box>
          {
            showSidebar &&
            <div className={`home-sidebar ${classes.sideBar} ${!isOpenSidebar && classes.hideSidebar}`}>
              <SidebarContentRender/>
            </div >
          }
        </Drawer>
      }
      {
        !below768 &&
        <div className={`home-sidebar ${classes.sideBar} ${!isOpenSidebar && classes.hideSidebar}`}>
          <SidebarContentRender/>
        </div >
      }
    </>
  );
};

export default AppSidebar;
