import React, { useCallback } from 'react';
import { CellNumberInput } from '@wix/patterns-fields';
import type { CellEditProps } from '../../types';
import { classes } from './Edit.st.css.js';

export const NumberEdit: React.FC<CellEditProps<number | null>> = ({
  value,
  onChange,
  onCommit,
  onCancel,
  inputRef,
}) => {
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        onCommit();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        onCancel();
      }
    },
    [onCommit, onCancel],
  );

  const handleBlur = useCallback(() => {
    onCommit();
  }, [onCommit]);

  return (
    <CellNumberInput
      inputRef={(instance) => {
        if (inputRef) {
          inputRef.current = instance;
        }
      }}
      size="small"
      border="none"
      value={value ?? undefined}
      onChange={(val) => onChange(val ?? null)}
      onKeyDown={handleKeyDown}
      onBlur={handleBlur}
      className={classes.numberInput}
    />
  );
};
