import { type FC, memo, useEffect, useRef } from 'react';

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

import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableHead from '@material-hu/components/design-system/Table/components/TableHead';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';

import DaysOfMonth from 'src/pages/dashboard/timeOff/components/calendar/DaysOfMonth';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getDaysInMonth } from 'src/utils/vacations';

export type RequestCalendarRowHeaderProps = {
  month: Date;
  noRequestsInMonth: boolean;
  count: number;
};

export const RequestCalendarRowHeader: FC<
  RequestCalendarRowHeaderProps
> = props => {
  const { month, count, noRequestsInMonth } = props;

  const scrollTopRef = useRef<HTMLInputElement>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const { t } = useLokaliseTranslation('time_off');

  useEffect(() => {
    if (scrollTopRef?.current && month) {
      timerRef.current = setTimeout(() => {
        scrollTopRef.current?.scrollIntoView({
          behavior: 'smooth',
          inline: 'center',
        });
      });
    }
    return () => clearTimeout(timerRef.current!);
  }, [scrollTopRef?.current, month]);

  const renderRowWithDaysOfMonth = () => {
    const amountDaysInMonth = getDaysInMonth(month);
    const daysToRender = noRequestsInMonth
      ? amountDaysInMonth.slice(0, 13)
      : amountDaysInMonth;

    return daysToRender.map((_, index) => (
      <DaysOfMonth
        key={`${month.toString()}-${index + 1}`}
        ref={scrollTopRef}
        month={month}
        day={index + 1}
      />
    ));
  };

  return (
    <HuTableHead>
      <HuTableRow headerRow>
        <HuTableCell
          align="left"
          sx={{
            position: 'sticky',
            left: 0,
            zIndex: 300,
            borderRight: theme =>
              `1px solid ${theme.palette.new.border.neutral.default}`,
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
          }}
          headerCell
        >
          <Typography
            variant="globalS"
            sx={{ fontWeight: 'fontWeightSemiBold' }}
          >
            {t('people', { count })}
          </Typography>
        </HuTableCell>
        {renderRowWithDaysOfMonth()}
      </HuTableRow>
    </HuTableHead>
  );
};

export default memo(RequestCalendarRowHeader);
