import React, { useMemo } from 'react';
import { format } from 'date-fns';
import { clsx } from 'clsx';
import type { ButtonProps } from '../../atoms';
import { Box, Button, Flex } from '../../atoms';
import { CalendarIcon } from '../../icon';
import type { DatePickerProps } from '.';
import { DatePicker } from '.';

export type DatePickerButtonProps = DatePickerProps & {
  placeholder?: React.ReactNode;
  format?: (date: Date) => string;
  size?: ButtonProps['size'];
};

export function DatePickerButton(
  props: DatePickerButtonProps
): React.ReactElement {
  const { size, placeholder, format: formatProps, disabled, ...rest } = props;

  const buttonProps = useMemo(() => {
    const variant: ButtonProps['variant'] = 'outline';
    const color: ButtonProps['color'] = 'gray';
    return { size, color, variant, disabled };
  }, [disabled, size]);

  const selectFormat = useMemo(() => {
    if (formatProps) return formatProps;
    return (date?: Date) => {
      return date ? format(date, 'yyyy년 MM월 dd일') : placeholder;
    };
  }, [formatProps, placeholder]);

  const className = useMemo(() => {
    return clsx(
      'date-picker-button',
      (disabled || props.readOnly) && 'disabled'
    );
  }, [disabled, props.readOnly]);

  return (
    <Box p="0" width="100%">
      <DatePicker
        customInput={
          <Button className={className} type="button" {...buttonProps}>
            <Flex align="center" gap="3" justify="between" width="100%">
              {rest.selected ? selectFormat(rest.selected) : placeholder}
              <CalendarIcon />
            </Flex>
          </Button>
        }
        wrapperClassName="full-width"
        {...rest}
        disabled={disabled}
      />
    </Box>
  );
}
