import { useQuery } from 'react-query';

import { IconClock } from '@material-hu/icons/tabler';

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

import { useAuth } from 'src/contexts/JWTContext';
import usePermissions from 'src/hooks/usePermissions';
import { clockRoutes } from 'src/pages/dashboard/clock/routes';
import { timeTrackingKeys } from 'src/pages/dashboard/timeTracking/queries';
import { getTimeTrackingPolicies } from 'src/services/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import itemsConfig from '../constants';
import useGetSidebarIcon from '../hooks/useSidebarIcon';
import { type SidebarItemProps } from '../types';
import { getItemIsActive } from '../utils';

const { key } = itemsConfig.clock;
const PATH = clockRoutes.base();

const VIEW_TIME_TRACKING = UserPermissions.VIEW_TIME_TRACKING;

const NavClockItem = (props: SidebarItemProps) => {
  const { isCollapsed, onClick, isActive: isActiveProp } = props;

  const { user } = useAuth();
  const { hasAll: canViewTimeTracking } = usePermissions([VIEW_TIME_TRACKING]);

  const userId = user?.id ?? 0;

  const { data: policies } = useQuery(
    timeTrackingKeys.policies(),
    () => getTimeTrackingPolicies(userId),
    {
      select: res => res.data,
      enabled: canViewTimeTracking && userId > 0,
    },
  );

  const isClockEnabled =
    canViewTimeTracking && !!policies?.clockingInWebEnabled;

  const { t } = useLokaliseTranslation([
    'dashboard_sidebar_app',
    'time_tracker',
  ]);

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconClock,
    key: 'Time tracking',
  });

  const isActive = isActiveProp ?? getItemIsActive(PATH);

  if (!policies || !canViewTimeTracking) return null;

  const title = isClockEnabled
    ? t('time_tracker:checker_clock')
    : t('time_tracker:trackings');

  return (
    <HuSidebarNavItem
      key={key}
      depth={0}
      title={title}
      icon={<Icon />}
      path={PATH}
      isCollapsed={isCollapsed}
      onClick={onClick}
      active={isActive}
    />
  );
};

export default NavClockItem;
