import { type SyntheticEvent } from 'react';

import Divider from '@material-hu/mui/Divider';
import Popover from '@material-hu/mui/Popover';
import Stack from '@material-hu/mui/Stack';
import { type SxProps, type Theme, useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

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

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

import { getTimeOffRequestWordings } from './utils';

const BANNER_SX: SxProps<Theme> = {
  alignItems: 'center',
  borderRadius: theme => theme.shape.borderRadiusM,
  flexDirection: 'row',
  justifyContent: 'space-between',
  p: 1,
};

type Props = {
  anchor: Element | null;
  closePopover: () => void;
  timeOffInfo: TimeOffPopoverInfo | null;
};

const TimeOffInfoPopover = ({ anchor, closePopover, timeOffInfo }: Props) => {
  const { t } = useLokaliseTranslation(['shifts', 'time_tracking_common']);
  const { palette } = useTheme();
  const { formatDate } = useFormatDate();

  if (!timeOffInfo) {
    return null;
  }

  const { typeDescription, additionalDetails } = getTimeOffRequestWordings(
    timeOffInfo.timeOff,
    t,
    formatDate,
  );
  const timeOffSpansAtLeastOneDay =
    timeOffInfo?.timeOff.consumptionType === 'FULL_DAY';
  const isWorkableTimeOff = timeOffInfo.timeOff.activityType === 'WORK';
  const hoursExpected = timeOffInfo.schedule.summaryHours.estimated !== 0;

  return (
    <Popover
      anchorEl={anchor}
      open={Boolean(anchor && timeOffInfo)}
      onClose={(e: SyntheticEvent) => {
        e.stopPropagation();
        closePopover();
      }}
      anchorOrigin={{
        vertical: 'bottom',
        horizontal: 'left',
      }}
      onClick={e => {
        e.stopPropagation();
      }}
    >
      <Stack sx={{ width: 312 }}>
        <Title
          title={timeOffInfo.timeOff.timeOffPolicyTypeName}
          description={typeDescription}
          sx={{ p: 2 }}
        />
        <Divider />
        <Stack sx={{ gap: 1, p: 2 }}>
          <Typography
            variant="globalS"
            sx={{
              fontWeight: 'fontWeightSemiBold',
            }}
          >
            {t('time_tracking_common:shifts')}
          </Typography>
          {timeOffInfo.schedule.timeSlots?.length > 0 && (
            <Stack
              sx={{
                flexDirection: 'row',
                flexWrap: 'wrap',
                gap: 0.5,
              }}
            >
              {timeOffInfo.schedule.timeSlots.map(ts => (
                <Pills
                  key={`${ts.startTime} - ${ts.endTime}`}
                  label={`${ts.startTime} - ${ts.endTime}`}
                  size="small"
                  hasIcon={false}
                  type={
                    isWorkableTimeOff || hoursExpected ? 'neutral' : 'disabled'
                  }
                />
              ))}
            </Stack>
          )}
          {timeOffSpansAtLeastOneDay && isWorkableTimeOff && (
            <Alert
              severity="info"
              title={t('time_tracking_common:additional_details')}
              description={additionalDetails}
            />
          )}
          {!timeOffSpansAtLeastOneDay && (
            <>
              <Stack
                sx={{
                  backgroundColor: palette.new.background.layout.default,
                  ...BANNER_SX,
                }}
              >
                <Typography
                  variant="globalXS"
                  sx={{ color: 'new.text.neutral.default' }}
                >
                  {t('shift_programmed_hours')}
                </Typography>
                <Typography
                  variant="globalXS"
                  sx={{ color: 'new.text.neutral.default' }}
                >
                  {t(
                    ...parseHoursAndMinutesDisplay(
                      timeOffInfo.schedule.summaryHours.scheduled,
                      true,
                    ),
                  )}
                </Typography>
              </Stack>
              <Stack
                sx={{
                  backgroundColor: palette.new.background.elements.inverted,
                  ...BANNER_SX,
                }}
              >
                <Typography
                  variant="globalXS"
                  sx={{ color: 'new.text.neutral.inverted' }}
                >
                  {t('time_tracking_common:to_meet_hours')}
                </Typography>
                <Typography
                  variant="globalXS"
                  sx={{ color: 'new.text.neutral.inverted' }}
                >
                  {t(
                    ...parseHoursAndMinutesDisplay(
                      timeOffInfo.schedule.summaryHours.estimated,
                      true,
                    ),
                  )}
                </Typography>
              </Stack>
            </>
          )}
        </Stack>
      </Stack>
    </Popover>
  );
};

export default TimeOffInfoPopover;
