import { type FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import {
  Button,
  Divider,
  IconButton,
  Popover,
  Stack,
  Typography,
} from '@mui/material';
import { IconChevronLeft, IconChevronRight } from '@tabler/icons-react';
import { format } from 'date-fns';
import es from 'date-fns/locale/es';

import { getCurrentLocale } from '../../../../../utils/languages';

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

const MonthPickerPopover: FC<MonthPickerPopoverProps> = ({
  anchorEl,
  open,
  onClose,
  selectedDate,
  onMonthSelect,
  onCurrentMonthClick,
}) => {
  const { t } = useTranslation('material_hu_only');
  const [displayYear, setDisplayYear] = useState(selectedDate.getFullYear());

  useEffect(() => {
    if (open) setDisplayYear(selectedDate.getFullYear());
  }, [open, selectedDate]);

  const locale = getCurrentLocale() || es;

  const monthNames = Array.from({ length: 12 }, (_, i) =>
    format(new Date(displayYear, i, 1), 'MMM', { locale }),
  );

  const selectedYear = selectedDate.getFullYear();
  const selectedMonth = selectedDate.getMonth();

  const handleMonthClick = (monthIndex: number) => {
    onMonthSelect(new Date(displayYear, monthIndex, 1));
    onClose();
  };

  const handleCurrentMonthClick = () => {
    onCurrentMonthClick?.();
    const today = new Date();
    onMonthSelect(new Date(today.getFullYear(), today.getMonth(), 1));
    onClose();
  };

  return (
    <Popover
      open={open}
      anchorEl={anchorEl}
      onClose={onClose}
      anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      transformOrigin={{ vertical: 'top', horizontal: 'center' }}
    >
      <Stack
        sx={{
          width: 260,
          backgroundColor: ({ palette }) =>
            palette.new.background.elements.default,
        }}
      >
        <Stack sx={{ p: 2 }}>
          <Stack
            sx={{
              alignItems: 'center',
              flexDirection: 'row',
              justifyContent: 'space-between',
              mb: 1.5,
            }}
          >
            <IconButton
              aria-label={t('date_period_selector.previous')}
              onClick={() => setDisplayYear(y => y - 1)}
              sx={{ p: 0.5 }}
            >
              <IconChevronLeft size={20} />
            </IconButton>

            <Typography
              variant="globalS"
              fontWeight={600}
            >
              {displayYear}
            </Typography>

            <IconButton
              aria-label={t('date_period_selector.next')}
              onClick={() => setDisplayYear(y => y + 1)}
              sx={{ p: 0.5 }}
            >
              <IconChevronRight size={20} />
            </IconButton>
          </Stack>

          <Stack
            sx={{
              display: 'grid',
              gridTemplateColumns: 'repeat(4, 1fr)',
              gap: 0.5,
            }}
          >
            {monthNames.map((name, index) => (
              <Button
                key={index}
                variant={
                  displayYear === selectedYear && index === selectedMonth
                    ? 'primary'
                    : 'tertiary'
                }
                onClick={() => handleMonthClick(index)}
                sx={{
                  fontSize: 13,
                  px: 0.5,
                  py: 1,
                  minWidth: 0,
                  textTransform: 'capitalize',
                }}
              >
                {name}
              </Button>
            ))}
          </Stack>
        </Stack>

        <Divider />

        <Stack sx={{ alignItems: 'center', p: 1 }}>
          <Button
            variant="tertiary"
            onClick={handleCurrentMonthClick}
          >
            {t('date_period_selector.current_month')}
          </Button>
        </Stack>
      </Stack>
    </Popover>
  );
};

export default MonthPickerPopover;
