import { IconHeartHandshake } from '@material-hu/icons/tabler';
import List from '@material-hu/mui/List';

import HuSidebarNavItem from '@material-hu/components/design-system/Sidebar/components/NavItem';

import {
  capabilityToi18nKey,
  useCustomServerTranslation,
} from 'src/hooks/useCustomServerTranslation';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import useGetSidebarIcon from '../hooks/useGetSidebarIcon';
import { type SidebarItemProps } from '../types';
import { getItemIsActive, getSubItemIsActive } from '../utils';

type ItemInfo = { isNew?: boolean } | undefined;

const PeopleExperienceItem = ({
  isCollapsed,
  onClick,
  isActive: isActiveProp,
}: SidebarItemProps) => {
  const { t } = useLokaliseTranslation(['backoffice_only', 'general']);
  const getCustomTitle = useCustomServerTranslation();
  const getIcon = useGetSidebarIcon();

  const title = getCustomTitle(
    capabilityToi18nKey(UserPermissions.VIEW_PEOPLE_EXPERIENCE),
    'TITLE_' + UserPermissions.VIEW_PEOPLE_EXPERIENCE,
  );

  const subItems: Array<{
    key: string;
    title: string;
    path: string;
    info: ItemInfo;
  }> = [
    {
      key: 'allSurveys',
      title: t('backoffice_only:dashboard_sidebar.all_surveys'),
      path: 'people-experience/surveys',
      info: undefined,
    },
    {
      key: 'questionsBank',
      title: t('general:questions_bank'),
      path: 'people-experience/questions-bank',
      info: undefined,
    },
    {
      key: 'surveyTemplates',
      title: t('backoffice_only:dashboard_sidebar.templates'),
      path: 'people-experience/templates',
      info: { isNew: true },
    },
  ];

  const isActive = isActiveProp ?? subItems.some(i => getItemIsActive(i.path));

  const renderSubItems = () => {
    if (isCollapsed) return null;
    return (
      <List
        disablePadding
        sx={{ '& > *:not(:last-child)': { mb: 0 } }}
      >
        {subItems.map((item, index) => (
          <HuSidebarNavItem
            key={item.key}
            depth={1}
            isLastChild={index === subItems.length - 1}
            active={getSubItemIsActive(item.path)}
            isCollapsed={isCollapsed}
            onClick={onClick}
            title={item.title}
            path={item.path}
            info={item.info}
          />
        ))}
      </List>
    );
  };

  return (
    <HuSidebarNavItem
      key="people-experience"
      depth={0}
      title={title}
      icon={getIcon({
        defaultIcon: IconHeartHandshake,
        key: 'People Experience',
      })}
      path="people-experience"
      isCollapsed={isCollapsed}
      onClick={onClick}
      active={isActive}
      open={isActive}
    >
      {renderSubItems()}
    </HuSidebarNavItem>
  );
};

export default PeopleExperienceItem;
