import { useNavigate, useLocation } from 'react-router-dom';

import HuTabs from '@material-hu/components/design-system/Tabs';
import { TabsProps as HuTabsProps } from '@material-hu/components/design-system/Tabs/types';

import { useAuth } from 'src/contexts/JWTContext';
import usePermissions from 'src/hooks/usePermissions';
import useOrgchartTitle from 'src/pages/dashboard/orgChart/hooks/useOrgchartTitle';
import { orgChartRoutes } from 'src/pages/dashboard/orgChart/routes';
import { insertIf } from 'src/utils/arrays';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { logOrgChartView } from 'src/utils/orgChart';
import { UserPermissions } from 'src/utils/permissions';

import { peopleRoutes } from 'src/components/dashboard/people/routes';

const { VIEW_ORGANIZATION_CHARTS } = UserPermissions;

export type ModuleTabsProps = {
  tabValue: HuTabsProps['value'];
};

const ModuleTabs = (props: ModuleTabsProps) => {
  const { tabValue } = props;

  const { user } = useAuth();
  const location = useLocation();
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('people');
  const orgChartTitle = useOrgchartTitle();

  const { hasAll: canViewOrgChart } = usePermissions([
    VIEW_ORGANIZATION_CHARTS,
  ]);

  const handleTabChange = (index: number) => {
    switch (index) {
      case 0:
        navigate(peopleRoutes.people());
        break;
      case 1:
        logOrgChartView(location.pathname);
        navigate(orgChartRoutes.thread.detail(user?.id!));
        break;
      default:
        break;
    }
  };

  const tabs = [
    { label: t('PEOPLE'), value: '0' },
    ...insertIf(canViewOrgChart, { label: orgChartTitle, value: '1' }),
  ];

  return (
    <HuTabs
      tabs={tabs}
      value={tabValue}
      onTabChange={(_, index) => handleTabChange(index)}
    />
  );
};

export default ModuleTabs;
