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

export const UrlEdit: React.FC<CellEditProps<string>> = ({
  value,
  onChange,
  onCommit,
  onCancel,
  inputRef,
  editTrigger,
}) => {
  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 (
    <div
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
      }}
    >
      <CellUrlInput
        inputRef={
          inputRef as React.MutableRefObject<
            InputImperativeActions | null | undefined
          >
        }
        value={value ?? ''}
        onChange={onChange}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
        autoSelect={
          !(typeof editTrigger === 'object' && editTrigger?.kind === 'type')
        }
        className={classes.urlInput}
      />
    </div>
  );
};
