'use client';

import { cn } from '@/lib';
import { useControllableValue } from 'ahooks';
import { FrameIcon } from '@/assets/components';
import isNumber from 'lodash/isNumber';

type NumberProps = {
  value?: number;
  onChange?: (value: number) => void;
  min?: number;
  max?: number;
  // 最小精度
  step?: number;
  defaultValue?: number;
} & React.HTMLAttributes<HTMLDivElement>;

export default function Number(props: NumberProps) {
  const { min = -9999999, max = 9999999, step = 1 } = props;
  const [value, setValue] = useControllableValue<number | undefined>(props);
  const className =
    'hover:cursor-pointer hover:bg-text-color/10 rounded-md p-1 text-text-color/60';
  return (
    <div className={cn('input-view justify-between')}>
      <span
        onClick={() =>
          isNumber(value) && setValue(Math.max(value - 1, min ?? 0))
        }
        className={className}
      >
        <FrameIcon />
      </span>
      <input
        className="[appearance:textfield] border-none bg-transparent text-center outline-none [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
        type="number"
        value={value ?? ''}
        onChange={(e) => {
          const val = e.target.value;
          setValue(val ? parseFloat(val) : undefined);
        }}
        min={min}
        max={max}
        step={step}
      />
      <span
        onClick={() =>
          isNumber(value) && setValue(Math.min(value + 1, max ?? 0))
        }
        className={cn(className, 'rotate-180')}
      >
        <FrameIcon />
      </span>
    </div>
  );
}
