import React, { useState } from 'react';
import { useTheme } from '@emotion/react';
import { Popup } from '../Popup';
import { StyledDateInput } from './style';
import { Input, InputProps } from '../Input';
import dayjs, { Dayjs } from 'dayjs';
import { Date } from './comp/Date';

export interface Props extends InputProps {}

export const DateInput = (props: Props) => {
  const [selectedDate, setSelectedDate] = useState<Dayjs>();
  const [value, setValue] = useState('');
  const [isDateOpen, setDateOpen] = useState<boolean>(false);
  const colors = useTheme();
  const checkPastDates = (day: Dayjs) => {
    return day.isBefore(dayjs(dayjs().format('YYYY-MM-DD')));
  };

  const handleChange = (val: Dayjs) => {
    setValue(val.format('MMM DD, YYYY'));
    setSelectedDate(val);
    setDateOpen(false);
    //@ts-ignore
    if (props.onChange) {
      //@ts-ignore
      props.onChange(dayjs(val.format('MM/DD/YYYY')).format());
    }
  };
  return (
    <StyledDateInput theme={{ ...colors }}>
      <Popup
        placement="bottom-start"
        padding={0}
        body={
          <Date
            defaultValue={selectedDate}
            disabledDates={checkPastDates}
            onChange={handleChange}
          />
        }
        onOpenChange={setDateOpen}
        trigger={isDateOpen}
      >
        <Input
          {...props}
          value={value}
          disableTrailing={false}
          onChange={() => {}}
          disabled
        />
      </Popup>
    </StyledDateInput>
  );
};
