import React, { useCallback } from 'react';
import { Input, Box } from '@wix/design-system';
import type { CellEditProps } from '../../types';
import { classes } from './Edit.st.css.js';

export const EmailEdit: React.FC<CellEditProps<string>> = ({
  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 (
    <Box width="100%" height="100%" verticalAlign="middle">
      <Input
        ref={(instance) => {
          if (inputRef) {
            inputRef.current = instance;
          }
        }}
        size="small"
        border="none"
        value={value ?? ''}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
        type="email"
        autoSelect={false}
        className={classes.emailInput}
      />
    </Box>
  );
};
