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

export const BooleanEdit: React.FC<CellEditProps<boolean>> = ({
  value,
  onChange,
  onCommit,
  onCancel,
}) => {
  const handleChange = useCallback(
    (checked: boolean) => {
      onChange(checked);
      onCommit();
    },
    [onChange, onCommit],
  );

  const stopClickPropagation = useCallback(
    (e: React.MouseEvent) => e.stopPropagation(),
    [],
  );

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        onChange(!value);
        onCommit();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        onCancel();
      }
    },
    [value, onChange, onCommit, onCancel],
  );

  return (
    <div
      onKeyDown={handleKeyDown}
      onClick={stopClickPropagation}
      className={classes.booleanEdit}
    >
      <CellCheckbox
        dataHook="boolean-checkbox"
        checked={!!value}
        onChange={handleChange}
        size="small"
      />
    </div>
  );
};
