import * as React from 'react';
import * as moment from 'moment';
import { Moment } from 'moment';
import { FastDatePicker } from 'components/ui';
import { isExactEmpty } from 'utils/isType';
import { FormTypes } from '../../types';

const MAXIMAL_NUMBER = 10000000;
const DEFAULT_FORMAT = 'YYYY-MM-DD HH:mm:ss';

function DatePicker(props: FormTypes.FormItem.FormAtomicDatepickerProps) {
  const { config, values, validateTrigger } = props;
  const {
    key,
    notModify,
    showTime,
    // option,
    placeholder,
    exportFormat,
    format,
  } = config;

  // states

  // handlers
  // eslint-disable-next-line react/destructuring-assignment
  const onChange = props[validateTrigger];

  const handleChange = React.useCallback((value: Moment) => {
    let formatValue: string | number = '';
    if (value) {
      switch (exportFormat) {
        case 'second':
          formatValue = value.valueOf() / 1000;
          break;
        case 'time':
          formatValue = value.format(format);
          break;
        case 'timestamp':
        default:
          formatValue = value.valueOf();
          break;
      }
    }
    if (onChange) onChange(formatValue);
  }, [exportFormat, format, onChange]);

  const formatInputValue = (value: any) => {
    if (typeof value === 'number' && value < MAXIMAL_NUMBER) return moment().subtract(value, 'days');
    return isExactEmpty(value) ? undefined : moment(value);
  };

  React.useEffect(() => {
    if (values[key]) {
      handleChange(formatInputValue(values[key]) as Moment);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <FastDatePicker
      disabled={notModify}
      value={formatInputValue(values[key])}
      placeholder={placeholder}
      picker="date"
      format={format || DEFAULT_FORMAT}
      allowClear
      showTime={showTime || false}
      onChange={handleChange}
    />
  );
}

export default DatePicker;
