import { Checkbox, DatePicker, Space } from 'antd';
import { useEffect, useState } from 'react';
import type { DatePickerProps } from 'antd/lib/date-picker';
import type { Moment } from 'moment';
import moment from 'moment';
import { useIntl } from 'umi';

type CustomDatePickerProps = DatePickerProps & {
  value?: any;
  onChange?: (val: any) => void;
};
const CustomDatePicker = ({ value, onChange }: CustomDatePickerProps) => {
  const [cValue, setValue] = useState<Moment | undefined | null>();
  const [checked, setChecked] = useState(false);
  const { formatMessage } = useIntl();

  const renderExtraFooter = () => (
    <>
      <Checkbox
        checked={checked}
        onChange={(e) => {
          setChecked(e.target.checked);
          if (e.target.checked) {
            setValue(undefined);
            onChange?.(0);
          } else {
            setValue(cValue);
            onChange?.(cValue);
          }
        }}
      >
        {formatMessage({ id: 'component.CustomDatePicker.always', defaultMessage: 'Permanent effect' })}
      </Checkbox>
    </>
  );
  useEffect(() => {
    if (value === 0) {
      setChecked(true);
      setValue(undefined);
    } else if (!value) {
      setChecked(false);
      setValue(undefined);
    } else {
      setChecked(false);
      setValue(moment(value));
    }
  }, [value]);
  return (
    <Space>
      <DatePicker
        placeholder={checked ? formatMessage({ id: 'component.CustomDatePicker.always', defaultMessage: 'Permanent effect' }) : formatMessage({ id: 'component.CustomDatePicker.select', defaultMessage: 'Please select date' })}
        value={cValue}
        disabledDate={(current) => {
          return current && current < moment().startOf('day');
        }}
        //   open={open}
        //   onOpenChange={(val) => setOpen(val)}
        onChange={(val) => {
          setValue(val);
          onChange?.(val);
        }}
        disabled={checked}
        showTime
      />
      {renderExtraFooter()}
    </Space>
  );
};

export default CustomDatePicker;
