import React, { useState, useCallback } from 'react';
import { faCircleXmark } from '@fortawesome/free-solid-svg-icons/faCircleXmark';
import { Input, INPUT_SIZES } from '../input';
import { useFocusWithin } from '../hooks/use-focus-within';
import { getValidityMessages, VALIDATION_RULE_TYPES, useDefaultValidationValues } from '../form-field';
import { jsx as _jsx } from "react/jsx-runtime";
export function SidebarMenuItemEditForm({
  initValue,
  itemKey,
  onExit,
  onSubmit,
  onChange,
  level,
  validity,
  editItemInputPlaceholder
}) {
  const [value, setInputValue] = useState(initValue);
  const hasError = validity?.type === VALIDATION_RULE_TYPES.ERROR && Boolean(validity?.value);
  const extraProps = {
    validity: {
      type: validity?.type,
      value: hasError
    },
    rightIcon: hasError ? faCircleXmark : null
  };
  const validationValues = useDefaultValidationValues();
  const validityMessages = getValidityMessages({
    validity,
    validationValues
  }).join('. ');
  if (validityMessages) {
    extraProps.iconTooltipText = validityMessages;
  }
  const handleCancel = useCallback(() => {
    setInputValue(initValue);
    onExit();
  }, [initValue]);
  const handleSubmit = useCallback(() => {
    if (hasError) {
      return;
    }
    onSubmit({
      key: itemKey,
      val: value,
      level
    });
    onExit();
  }, [value, validity]);
  const handleKeyDown = useCallback(e => {
    if (e.key === 'Esc' || e.key === 'Escape') {
      handleCancel();
    }
  }, [initValue]);
  const focusWithinProps = useFocusWithin({
    onBlur: handleCancel
  });
  return (
    /*#__PURE__*/
    // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
    _jsx("form", {
      "test-id": `sidebar-menu-item-form-${itemKey}`,
      onKeyDown: handleKeyDown,
      onBlur: focusWithinProps.onBlur,
      onSubmit: e => {
        e.preventDefault();
        handleSubmit();
      },
      children: /*#__PURE__*/_jsx(Input, {
        shouldDisplayControls: true,
        fieldClass: "sidebar-menu-item-input",
        className: "controllable-field",
        placeholder: editItemInputPlaceholder,
        autoFocus: true,
        value: value,
        onCancel: handleCancel,
        onChange: e => {
          setInputValue(e.target.value);
          onChange?.({
            key: itemKey,
            val: e.target.value,
            level
          });
        },
        fieldTestId: `sidebar-menu-item-input-${itemKey}`,
        onSubmit: handleSubmit,
        inputSize: INPUT_SIZES.SM,
        ...extraProps
      })
    })
  );
}