import { RefObject } from 'react';

import {
  NumberDecrementStepper,
  NumberIncrementStepper,
  NumberInput,
  NumberInputField,
  NumberInputProps,
  NumberInputStepper,
} from '@chakra-ui/react';

import { FormGroup } from '@/components/form/FormGroup';
import { UseFormidableReturn } from '@/components/form/Formidable';

export type FormNumberProps = Pick<
  NumberInputProps,
  'step' | 'defaultValue' | 'min' | 'max'
> & {
  form: UseFormidableReturn;
  variableName: string;
  ref?: RefObject<any>;
  label?: string;
  placeholder?: string;
  isRequired?: boolean;
};

export const FormNumber = ({
  form,
  variableName,
  ref,
  placeholder,
  step,
  min,
  max,
  defaultValue,
  ...rest
}: FormNumberProps) => {
  return (
    <FormGroup
      isModify={form.isModify[variableName]}
      onRestore={() => form.restoreValue({ [variableName]: true })}
      {...rest}
    >
      <NumberInput
        ref={ref}
        value={form.values[variableName]}
        onChange={(_, value) => form.setValues({ [variableName]: value })}
        step={step}
        defaultValue={defaultValue}
        min={min}
        max={max}
      >
        <NumberInputField />
        <NumberInputStepper>
          <NumberIncrementStepper />
          <NumberDecrementStepper />
        </NumberInputStepper>
      </NumberInput>
    </FormGroup>
  );
};
