import { indexOf } from 'lodash-es';
import { type GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';
import { IconMapPinExclamation } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

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

import { Incidence } from 'src/types/timeTracking';
import { type LokaliseTFunction } from 'src/utils/i18n';

import { HIDDEN_INCIDENCES, NON_TAG_INCIDENCES } from '../../constants';

import HuIncidenceTag from './IncidenceTag';

type DrawerProps = {
  t: LokaliseTFunction;
};

const INCIDENCES_ORDER = [
  Incidence.ABSENT,
  Incidence.LOCATION_INCIDENCE,
  Incidence.LATE,
  Incidence.AUTO_CLOSE,
];

const sortedIncidences: Incidence[] = Object.keys(Incidence)
  .map(key => Incidence[key as keyof typeof Incidence])
  .filter(key => ![...HIDDEN_INCIDENCES, ...NON_TAG_INCIDENCES].includes(key))
  .sort((a, b) => indexOf(INCIDENCES_ORDER, a) - indexOf(INCIDENCES_ORDER, b));

const getIncidencesDrawerContent: GetDrawerConfiguration<DrawerProps> = ({
  closeDrawer,
  t,
}) => ({
  children: (
    <Stack
      sx={{
        flex: 1,
        justifyContent: 'space-between',
        pb: 2,
      }}
    >
      <Stack
        sx={{
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
          borderRadius: 1,
          p: 2,
        }}
      >
        <HuTitle
          variant="M"
          title={t('time_tracker:incidences')}
          description={t('time_tracker:incidences_hint')}
        />
        <Stack
          sx={{
            alignItems: 'center',
            flexDirection: 'row',
            flexWrap: 'wrap',
            gap: 1,
            my: 2,
          }}
        >
          {sortedIncidences.map(i =>
            i === Incidence.LOCATION_INCIDENCE ? (
              <HuAvatar
                key={i}
                size="small"
                Icon={IconMapPinExclamation}
                color="warning"
              />
            ) : (
              <HuIncidenceTag
                key={i}
                type={i}
                count={0}
                hideCount
                disableTooltip
              />
            ),
          )}
        </Stack>
        <Stack sx={{ gap: 2 }}>
          {sortedIncidences.map(i => (
            <HuTitle
              key={i}
              variant="S"
              title={t(`time_tracker:${i}`)}
              description={t('time_tracker:incidence_meaning', {
                context: i,
              })}
            />
          ))}
        </Stack>
      </Stack>
    </Stack>
  ),
  title: t('time_tracker:incidences'),
  hasBackButton: true,
  onClose: closeDrawer,
});

export default getIncidencesDrawerContent;
