import React, { useMemo } from 'react';
import { format } from 'date-fns';
import { clsx } from 'clsx';
import type { ButtonProps } from '@/atoms/button.type';
import { Button } from '@/atoms/button';
import { TextField } from '@/atoms/text-field';
import { Box } from '@/atoms/box';
import { CalendarIcon } from '../../icon';
import type { DatePickerProps } from '.';
import { DatePicker } from '.';

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

export function DatePickerButton(
  props: DatePickerButtonProps
): React.ReactNode {
  const { size, format: formatProps, disabled, ...rest } = props;
  const placeholder = rest.placeholder || '날짜를 선택해주세요';

  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일') : '';
    };
  }, [formatProps]);

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

  const placeholderVisible = useMemo(() => {
    return rest.selected ? '' : 'placeholder-visible';
  }, [rest.selected]);

  return (
    <Box p="0" width="100%">
      <DatePicker
        customInput={
          <Button asChild className={className} type="button" {...buttonProps}>
            <TextField.Root
              className={placeholderVisible}
              placeholder={placeholder || ''}
              value={rest.selected ? selectFormat(rest.selected) : placeholder}
            >
              <TextField.Slot className="hide-slot" />
              <TextField.Slot>
                <CalendarIcon />
              </TextField.Slot>
            </TextField.Root>
          </Button>
        }
        wrapperClassName="full-width"
        {...rest}
        disabled={disabled}
      />
    </Box>
  );
}
