import type { ElementRef } from 'react';
import React, { forwardRef } from 'react';
import type { DatePickerProps as ReactDatePickerProps } from 'react-datepicker';
import ReactDatePicker from 'react-datepicker';
import { IconButton } from '../../atoms/icon-button';
import { Flex } from '../../atoms/flex';
import { ChevronLeftIcon, ChevronRightIcon } from '../../icon';
import { Heading } from '../../atoms/heading';

export type DatePickerProps = ReactDatePickerProps & {
  fullWidth?: boolean;
};
type DatePickerRef = ElementRef<typeof ReactDatePicker>;

export const DatePicker = forwardRef<DatePickerRef, DatePickerProps>(
  (props, ref): React.ReactNode => {
    const { fullWidth, ...rest } = props;
    const fullWidthClassName = fullWidth ? 'full-width' : '';
    return (
      <Flex p="0" width="100%">
        <ReactDatePicker
          dateFormat="YYYY/MM/dd"
          nextMonthButtonLabel="다음 달"
          placeholderText="YYYY/mm/dd"
          popperProps={{ strategy: 'fixed' }}
          previousMonthButtonLabel="이전 달"
          ref={ref}
          renderCustomHeader={renderCustomHeader}
          showPopperArrow={false}
          timeIntervals={10}
          {...rest}
          calendarClassName={`tipp_datePicker_calendar ${rest.calendarClassName || ''}`}
          timeCaption="시간"
          wrapperClassName={`tipp_datePicker ${fullWidthClassName} ${rest.wrapperClassName || ''}`}
        />
      </Flex>
    );
  }
);

DatePicker.displayName = 'DatePicker';

const renderCustomHeader: ReactDatePickerProps['renderCustomHeader'] = (
  props
) => {
  const {
    date,
    decreaseMonth,
    increaseMonth,
    prevMonthButtonDisabled,
    nextMonthButtonDisabled,
  } = props;

  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- date가 undefined일 수 있음
  const year = date ? new Date(date).getFullYear() : '-';
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- date가 undefined일 수 있음
  const month = date ? new Date(date).getMonth() + 1 : '-';

  return (
    <Flex align="center" justify="between" pb="2" pl="2" pr="2">
      <IconButton
        disabled={prevMonthButtonDisabled}
        onClick={decreaseMonth}
        type="button"
        variant="ghost"
      >
        <ChevronLeftIcon />
      </IconButton>
      <Flex gap="3">
        <Heading variant="heading4" weight="regular">
          {year}년
        </Heading>
        <Heading variant="heading4" weight="regular">
          {month}월
        </Heading>
      </Flex>

      <IconButton
        disabled={nextMonthButtonDisabled}
        onClick={increaseMonth}
        type="button"
        variant="ghost"
      >
        <ChevronRightIcon />
      </IconButton>
    </Flex>
  );
};

// DatePicker.displayName = 'DatePicker';
