import { FC, SyntheticEvent } from 'react';
import { TFunction } from 'react-i18next';

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

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { DaySummary, Incidence } from 'src/types/timeTracking';
import { formatToTime } from 'src/utils/date';
import { LokaliseTFunction, useLokaliseTranslation } from 'src/utils/i18n';
import { formatCompleteDecimalHours } from 'src/utils/timeTracking';

import { UNDERWORKED_TOLERANCE } from '../../constants';
import { searchFirstStart } from '../../EmployeeTimesheet/utils';

import HuIncidenceTag from './IncidenceTag';

type Props = {
  anchor: any;
  closePopover: () => void;
  isOpen: boolean;
  type: Incidence | 'MULTIPLE_INCIDENCES';
  daySummaryInfo: DaySummary;
  incidences?: Incidence[];
};

type PopoverIncidence = Extract<Incidence, 'LATE' | 'UNDERWORKED'>;

const CONTENT: Record<
  PopoverIncidence,
  (daySummary: DaySummary, t: TFunction | LokaliseTFunction) => React.ReactNode
> = {
  [Incidence.LATE]: (
    { timeTrackingEntries, timeSlots, latenessTolerance },
    t,
  ) => {
    const firstStartEntry = searchFirstStart(timeTrackingEntries);
    return (
      <Stack sx={{ gap: 2 }}>
        <Stack
          sx={{
            alignItems: 'center',
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}
        >
          <HuTitle
            title={t('REGULATORY_HOUR')}
            description={
              latenessTolerance
                ? t('TOLERANCE', { minutes: latenessTolerance })
                : ''
            }
            variant="S"
          />
          <HuPills
            type="neutral"
            label={timeSlots?.[0]?.startTime || ''}
            hasIcon={false}
            size="small"
          />
        </Stack>
        <Stack
          sx={{
            alignItems: 'center',
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}
        >
          <HuTitle
            title={t('ENTRY_HOUR')}
            variant="S"
          />
          <HuPills
            type="warning"
            label={formatToTime(
              firstStartEntry?.time ? new Date(firstStartEntry.time) : '--:--',
            )}
            hasIcon={false}
            size="small"
          />
        </Stack>
      </Stack>
    );
  },
  [Incidence.UNDERWORKED]: ({ estimatedHours, workedHours }, t) => (
    <Stack sx={{ gap: 2 }}>
      <Stack
        sx={{
          alignItems: 'center',
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
      >
        <HuTitle
          title={t('WORKED_HOURS')}
          description={t('TOLERANCE', { minutes: UNDERWORKED_TOLERANCE })}
          variant="S"
        />
        <Typography
          variant="globalS"
          sx={{ color: ({ palette }) => palette.new.text.neutral.default }}
        >
          {formatCompleteDecimalHours(workedHours)}
        </Typography>
      </Stack>
      <Stack
        sx={{
          alignItems: 'center',
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
      >
        <HuTitle
          title={t('PENDING_TIME')}
          variant="S"
        />
        <HuPills
          type="warning"
          label={formatCompleteDecimalHours(estimatedHours - workedHours)}
          hasIcon={false}
          size="small"
        />
      </Stack>
    </Stack>
  ),
};

const IncidencePopover: FC<Props> = props => {
  const { anchor, closePopover, daySummaryInfo, isOpen, type, incidences } =
    props;
  const { t } = useLokaliseTranslation('time_tracker');
  const HuGoThemeProvider = useHuGoTheme();

  if (!incidences) {
    return null;
  }

  const isLateOrUnderworked =
    type === Incidence.LATE || type === Incidence.UNDERWORKED;

  return (
    <HuGoThemeProvider>
      <Popover
        anchorEl={anchor}
        open={isOpen}
        onClose={(e: SyntheticEvent) => {
          e.stopPropagation();
          closePopover();
        }}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        onClick={e => {
          e.stopPropagation();
        }}
        closeAfterTransition
        slotProps={{
          paper: {
            sx: {
              bgcolor: ({ palette }) => palette.new.background.elements.default,
              border: ({ palette }) =>
                `1px solid ${palette.new.border.neutral.default}`,
            },
          },
        }}
      >
        {type !== 'MULTIPLE_INCIDENCES' && isLateOrUnderworked && (
          <Stack sx={{ p: 2, width: '338px' }}>
            <Stack sx={{ gap: 0.5 }}>
              <HuTitle
                title={t(type)}
                description={t('POPOVER_DESCRIPTION', { context: type })}
                variant="S"
              />
            </Stack>
            <Stack sx={{ mt: 2 }}>
              {CONTENT[type]?.(daySummaryInfo, t) || null}
            </Stack>
          </Stack>
        )}
        {type === 'MULTIPLE_INCIDENCES' && (
          <Stack sx={{ py: 2, width: 363 }}>
            <HuTitle
              title={t('INCIDENCES')}
              description={t('INCIDENCES_POPOVER_DESCRIPTION')}
              variant="S"
              sx={{ px: 2 }}
            />
            <Stack
              sx={{
                alignItems: 'center',
                borderTop: ({ palette }) =>
                  `1px solid ${palette.new.border.neutral.default}`,
                flexDirection: 'row',
                flexWrap: 'wrap',
                gap: 2,
                mt: 2,
                pt: 2,
                px: 2,
              }}
            >
              {incidences.map(incidence => (
                <HuIncidenceTag
                  key={incidence}
                  type={incidence}
                  count={0}
                  hideCount
                  disableTooltip
                />
              ))}
            </Stack>
          </Stack>
        )}
      </Popover>
    </HuGoThemeProvider>
  );
};

export default IncidencePopover;
