import React, { useEffect, useState } from 'react';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, InputNumber, Space } from 'antd';
import { InputNumberProps } from 'antd/es/input-number';

const NumberBox: React.FC<InputNumberProps> = (props) => {
  // 使用state hooks来定义value和setValue
  const [value, setValue] = useState<number>(1);

  // 定义增加和减少的函数
  const handleIncrement = () => {
    // 不能大于最大
    if (props?.max && value >= Number(props?.max)) return;
    props?.onChange?.(value + 1);
    setValue(value + 1);
  };

  const handleDecrement = () => {
    // 不能低于最小
    if (props?.min && value <= Number(props?.min)) return;
    props?.onChange?.(value - 1);
    setValue(value - 1);
  };
  // 监听value的变化
  useEffect(() => {
    if (!props?.value) return;
    setValue(Number(props?.value) || 1);
  }, [props?.value]);
  return (
    <Space.Compact block style={{ width: 'auto' }}>
      <Button icon={<MinusOutlined />} onClick={handleDecrement} />
      <InputNumber
        {...props}
        controls={false}
        style={{ width: '42px' }}
        value={value}
      />
      <Button icon={<PlusOutlined />} onClick={handleIncrement} />
    </Space.Compact>
  );
};

export default NumberBox;
