import { useMemo } from 'react';

import Stack from '@material-hu/mui/Stack';

import HuTitle from '@material-hu/components/design-system/Title';

import { useLokaliseTranslation } from 'src/utils/i18n';

import NavigationSidebarRow from './NavigationSidebarRow';
import {
  type NavigationSidebarGroup,
  type NavigationSidebarItemUser,
} from './types';
import { resolveSidebarGroups } from './utils';

type NavigationSidebarProps<T> = {
  items?: T[];
  groups?: NavigationSidebarGroup<T>[];
  selectedId: number | string | null;
  getItemId: (item: T) => number | string;
  getUser: (item: T) => NavigationSidebarItemUser;
  getPrimaryLabel: (item: T) => string;
  isCompleted: (item: T) => boolean;
  onSelect: (item: T) => void;
};

const NavigationSidebar = <T,>(props: NavigationSidebarProps<T>) => {
  const {
    items,
    groups,
    selectedId,
    getItemId,
    getUser,
    getPrimaryLabel,
    isCompleted,
    onSelect,
  } = props;

  const { t } = useLokaliseTranslation(['performance']);

  const resolvedGroups = useMemo<NavigationSidebarGroup<T>[]>(
    () => resolveSidebarGroups({ items, groups }),
    [groups, items],
  );

  if (resolvedGroups.length === 0) return null;

  return (
    <Stack sx={{ gap: 2, width: '100%' }}>
      {resolvedGroups.map((group, groupIndex) => (
        <Stack
          key={group.titleKey ?? `group-${groupIndex}`}
          sx={{ gap: 2 }}
        >
          {group.titleKey && (
            <HuTitle
              variant="S"
              title={t(group.titleKey)}
            />
          )}
          <Stack sx={{ gap: 1 }}>
            {group.items.map(item => {
              const itemId = getItemId(item);
              return (
                <NavigationSidebarRow
                  key={itemId}
                  item={item}
                  isSelected={selectedId === itemId}
                  isCompleted={isCompleted(item)}
                  primaryLabel={getPrimaryLabel(item)}
                  user={getUser(item)}
                  onSelect={onSelect}
                />
              );
            })}
          </Stack>
        </Stack>
      ))}
    </Stack>
  );
};

export default NavigationSidebar;
