import { Space, Modal, Button } from 'antd';
import { useEffect, useRef, useState } from 'react';
import type { DatePickerProps } from 'antd/lib/date-picker';
import moment from 'moment';

import CustomDatePicker from './index';
import { useIntl, FormattedMessage } from 'umi';

type CustomBatchDatePickerProps = DatePickerProps & {
  value?: any;
  onChange?: (val: any) => void;
  applyAll?: (val: any) => void;
  applyNew?: (val: any) => void;
};
const CustomBatchDatePicker = ({
  value,
  onChange,
  applyAll,
  applyNew,
}: CustomBatchDatePickerProps) => {
  const { formatMessage } = useIntl();
  const [open, setOpen] = useState(false);
  const [cValue, setValue] = useState(value);
  const ref = useRef(false);
  useEffect(() => {
    if (ref.current && (cValue || cValue === 0)) {
      setOpen(true);
    }
  }, [cValue]);
  useEffect(() => {
    ref.current = true;
  }, []);
  return (
    <Space style={{ width: '100%' }}>
      <FormattedMessage id="component.CustomBatchDatePicker.label" />
      <CustomDatePicker
        value={cValue}
        onChange={(val) => {
          setValue(val);
          onChange?.(val);
        }}
      />
      <Modal
        open={open}
        title={<FormattedMessage id="component.CustomBatchDatePicker.label" />}
        onCancel={() => {
          setOpen(false);
        }}
        // onOk={() => setOpen(false)}
        footer={
          <Space>
            <Button
              onClick={() => {
                setOpen(false);
                applyAll?.(cValue === 0 ? cValue : cValue.valueOf());
              }}
              type="primary"
            >
              <FormattedMessage id="component.CustomBatchDatePicker.apply.all" />
            </Button>
            <Button
              onClick={() => {
                setOpen(false);
                applyNew?.(cValue === 0 ? cValue : cValue.valueOf());
              }}
              type="primary"
            >
              <FormattedMessage id="component.CustomBatchDatePicker.apply.add" />
            </Button>{' '}
          </Space>
        }
      >
        {cValue === 0
          ? formatMessage({ id: 'component.CustomBatchDatePicker.apply.all.confirm' })
          : `${formatMessage({ id: 'component.CustomBatchDatePicker.apply.add.confirm' })}${moment(
              cValue,
            ).format('YYYY-MM-DD HH:mm:ss')}？`}
      </Modal>
    </Space>
  );
};

export default CustomBatchDatePicker;
