import React, { useState } from 'react';
import { useUpdateEffect } from 'react-use';
import NumberInput, { NumberInputProps } from '../../../number-input';

export interface RangeInputProps {
  fieldProps?: {
    props?: [NumberInputProps?, NumberInputProps?];
    value?: [string, string];
    onChange?: (value: [string, string] | undefined) => void;
  };
}

export const RangeInput: React.FC<RangeInputProps> = ({ fieldProps }) => {
  const [rangeValue, setRangeValue] = useState<undefined | string[]>(
    () => fieldProps?.value || ['', ''],
  );

  const triggerChange = (changedValue: [string, string] | undefined) => {
    if (fieldProps?.onChange) {
      fieldProps.onChange(changedValue);
    }
  };

  const onMinChange = (value: number) => {
    fieldProps?.props?.[0]?.onChange?.(value);
  };

  const onMaxChange = (value: number) => {
    fieldProps?.props?.[0]?.onChange?.(value);
  };

  const onMinBlur = (value: string) => {
    const result: [string, string] | undefined =
      !value && !rangeValue?.[1] ? undefined : [value, rangeValue?.[1] || ''];

    if (result && result[0] && result[1] && Number(result[0]) > Number(result[1])) {
      // eslint-disable-next-line prefer-destructuring
      result[1] = result[0];
    }

    const equal = JSON.stringify(result) === JSON.stringify(fieldProps?.value);

    // 与原来相等不触发
    if (!equal) {
      setRangeValue(result);
      triggerChange(result);
    }

    fieldProps?.props?.[0]?.onBlur?.(value);
  };

  const onMaxBlur = (value: string) => {
    const result: [string, string] | undefined =
      !rangeValue?.[0] && !value ? undefined : [rangeValue?.[0] || '', value];

    if (result && result[0] && result[1] && Number(result[0]) > Number(result[1])) {
      // eslint-disable-next-line prefer-destructuring
      result[0] = result[1];
    }

    const equal = JSON.stringify(result) === JSON.stringify(fieldProps?.value);
    // 与原来相等不触发
    if (!equal) {
      setRangeValue(result);
      triggerChange(result);
    }

    fieldProps?.props?.[1]?.onBlur?.(value);
  };

  useUpdateEffect(() => {
    if (JSON.stringify(rangeValue) !== JSON.stringify(fieldProps?.value)) {
      setRangeValue(fieldProps?.value);
    }
  }, [setRangeValue, fieldProps?.value]);

  return (
    <div>
      <NumberInput
        {...fieldProps?.props?.[0]}
        value={rangeValue?.[0]}
        onChange={onMinChange}
        onBlur={onMinBlur}
        style={{ width: 'calc(50% - 12px)', ...fieldProps?.props?.[0]?.style }}
      />
      <span
        style={{
          display: 'inline-block',
          width: '24px',
          lineHeight: '32px',
          textAlign: 'center',
        }}
      >
        ~
      </span>
      <NumberInput
        {...fieldProps?.props?.[1]}
        value={rangeValue?.[1]}
        onChange={onMaxChange}
        onBlur={onMaxBlur}
        style={{ width: 'calc(50% - 12px)', ...fieldProps?.props?.[1]?.style }}
      />
    </div>
  );
};
