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

import useFormatDate from 'src/hooks/useFormatDate';
import { type PairedEntry } from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { endIsNightShifted } from 'src/utils/timeTracking';

import EntryExitPairChip from './EntryExitPairChip';

const PLUS_ONE = '+1';

type Props = {
  entryPairs: PairedEntry[];
};

const EntryPairs = ({ entryPairs }: Props) => {
  const { t } = useLokaliseTranslation('time_tracker');
  const { formatDate } = useFormatDate();

  return (
    <Stack sx={{ gap: 1, flexDirection: 'row' }}>
      {entryPairs.map(pair => {
        const startTime = pair.start?.time
          ? formatDate(pair.start.time, 'HH:mm')
          : null;
        const endTime = pair.end?.time
          ? formatDate(pair.end.time, 'HH:mm')
          : null;
        let isNightShift = false;
        if (pair.start?.time && pair.end?.time) {
          isNightShift = endIsNightShifted(pair.end.time, pair.start.time);
        }

        return (
          <Stack
            key={pair.id}
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 1,
              flexWrap: 'wrap',
            }}
          >
            <EntryExitPairChip
              startTime={startTime}
              endTime={endTime}
            />
            {!endTime && startTime && (
              <Typography variant="globalXXS">{t('ongoing')}</Typography>
            )}
            {isNightShift && (
              <Typography
                variant="globalXXS"
                sx={{
                  color: ({ palette }) => palette.new.text.feedback.info,
                  fontSize: 10,
                  fontWeight: 'fontWeightSemiBold',
                  position: 'relative',
                  top: -4,
                }}
              >
                {PLUS_ONE}
              </Typography>
            )}
          </Stack>
        );
      })}
    </Stack>
  );
};

export default EntryPairs;
