import useFormatDate from '@hooks/useFormatDate';
import { IconButton, Stack, Typography, useTheme } from '@mui/material';
import {
  IconChevronDown,
  IconChevronLeft,
  IconChevronRight,
} from '@tabler/icons-react';

import { type CustomCalendarHeaderProps } from './types';

const CustomCalendarHeader = (props: CustomCalendarHeaderProps) => {
  const { onMonthChange, slotProps, ...headerProps } = props;
  const { previousMonthText, nextMonthText, changeMonthText } = slotProps;
  const { formatDate } = useFormatDate({ useV6Provider: true });
  const theme = useTheme();

  const formattedMonth = formatDate(headerProps.currentMonth, 'MMMM yyyy');

  const handlePreviousMonthClick = () => {
    const newDate = new Date(headerProps.currentMonth);
    newDate.setMonth(newDate.getMonth() - 1);
    onMonthChange(newDate, 'right');
  };

  const handleNextMonthClick = () => {
    const newDate = new Date(headerProps.currentMonth);
    newDate.setMonth(newDate.getMonth() + 1);
    onMonthChange(newDate, 'left');
  };

  const handleMonthButtonClick = () => {
    // This triggers the year selection view
    headerProps.onViewChange?.('year');
  };

  return (
    <Stack
      sx={{
        alignItems: 'center',
        flexDirection: 'row',
        justifyContent: 'space-between',
      }}
    >
      <IconButton
        aria-label={previousMonthText}
        onClick={handlePreviousMonthClick}
      >
        <IconChevronLeft size={24} />
      </IconButton>
      <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
        <Typography
          variant="globalS"
          sx={{
            color: theme.palette.new.text.neutral.default,
            fontWeight: 'fontWeightSemiBold',
          }}
        >
          {formattedMonth}
        </Typography>
        <IconButton
          onClick={handleMonthButtonClick}
          aria-label={changeMonthText}
          aria-haspopup="true"
          sx={{
            p: 0.5,
            color: theme.palette.new.text.neutral.default,
            '& svg': {
              stroke: theme.palette.new.text.neutral.default,
            },
          }}
        >
          <IconChevronDown size={16} />
        </IconButton>
      </Stack>
      <IconButton
        aria-label={nextMonthText}
        onClick={handleNextMonthClick}
      >
        <IconChevronRight size={24} />
      </IconButton>
    </Stack>
  );
};

export default CustomCalendarHeader;
