import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';

import { addMonths, subMonths } from 'date-fns';
import { capitalize } from 'lodash-es';
import { IconChevronLeft, IconChevronRight } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { logEvent } from 'src/config/logging';
import useFormatDate from 'src/hooks/useFormatDate';
import { restoreMonthWithFirstPage } from 'src/pages/dashboard/timeOff/queries';
import { EventName } from 'src/types/amplitude';
import { type VacationsFilterValues } from 'src/types/vacations';

const logMonthNavigation = () => {
  logEvent(EventName.TIME_OFF_CALENDAR_MONTHLY_NAVIGATION);
};

type MonthInputProps = {
  name?: string;
  filters: VacationsFilterValues;
};

const MonthInput: FC<MonthInputProps> = props => {
  const { name, filters } = props;

  const { watch, setValue } = useFormContext();
  const { formatDate } = useFormatDate();

  const month = watch('month');

  const handleAddMonth = () => {
    const date = watch('month');
    restoreMonthWithFirstPage(date, filters);
    setValue(name, addMonths(date, 1));
    logMonthNavigation();
  };

  const handleSubMonth = () => {
    const date = watch('month');
    restoreMonthWithFirstPage(date, filters);
    setValue(name, subMonths(date, 1));
    logMonthNavigation();
  };

  return (
    <Stack
      flexDirection="row"
      alignItems="center"
      justifyContent="start"
      sx={{ p: 2 }}
    >
      <IconButton onClick={handleSubMonth}>
        <IconChevronLeft fontSize="small" />
      </IconButton>
      <Typography
        variant="globalM"
        fontWeight="fontWeightBold"
      >
        {capitalize(formatDate(month, 'MMMM yyyy'))}
      </Typography>
      <IconButton onClick={handleAddMonth}>
        <IconChevronRight fontSize="small" />
      </IconButton>
    </Stack>
  );
};

export default MonthInput;
