import { forwardRef, useMemo } from 'react';
import { ReactDatePickerProps } from 'react-datepicker';

import { useDateFnsLocale } from '../../../../core/hooks/useDateFnsLocale';
import { useTranslation } from '../../../../core/hooks/useTranslation';
import { useTestIdAttribute } from '../../../../hooks/useTestIdAttribute';
import { assertEmptyObject } from '../../../../utils/assertEmptyObject';

import { TunedReactDatePicker } from './styled';

/** Props for {@link DatePicker} */
export interface DatePickerProps {
  testId?: string;
  value?: Date;
  onChange(date: Date): void;
}

export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>((props, ref) => {
  const { testId, value, onChange, ...restProps } = props;
  assertEmptyObject(restProps);

  const dateFnsLocale = useDateFnsLocale();
  const { t } = useTranslation();
  const testIdAttribute = useTestIdAttribute();

  const calendarContainer = useMemo<ReactDatePickerProps['calendarContainer']>(() => {
    return (containerProps) => {
      return (
        <div ref={ref} className={containerProps.className} {...{ [testIdAttribute]: testId }}>
          {containerProps.children}
        </div>
      );
    };
  }, [testIdAttribute, testId, ref]);

  return (
    <TunedReactDatePicker
      calendarContainer={calendarContainer}
      chooseDayAriaLabelPrefix={t('ui.datePicker.chooseDayPrefix')}
      dropdownMode="select"
      inline
      locale={dateFnsLocale}
      nextMonthButtonLabel={t('ui.datePicker.nextMonth')}
      nextYearButtonLabel={t('ui.datePicker.nextYear')}
      onChange={onChange}
      popperPlacement="bottom-end"
      previousMonthButtonLabel={t('ui.datePicker.previousMonth')}
      previousYearButtonLabel={t('ui.datePicker.previousYear')}
      selected={value}
      showMonthDropdown
      showYearDropdown
      strictParsing
    />
  );
});
