import { useId } from "react";
import { spaceDelimitedList } from "../../utils/spaceDelimitedList";
import { useLabel } from "../useLabel/useLabel";
import type { UseTextFieldProps, UseTextFieldReturn } from "./types";

export function useTextField(props: UseTextFieldProps): UseTextFieldReturn {
  const {
    isDisabled = false,
    isReadOnly = false,
    isRequired = false,
    inputElementType = "input",
  } = props;
  const { labelProps, fieldProps } = useLabel(props);

  const descriptionId = useId();
  const descriptionProps = { id: descriptionId };

  const errorMessageId = useId();
  const errorMessageProps = { id: errorMessageId };

  const ariaDescribedBy = spaceDelimitedList([
    props.description && descriptionId,
    props.errorMessage && errorMessageId,
    props["aria-describedby"],
  ]);

  return {
    descriptionProps,
    errorMessageProps,
    labelProps,
    inputProps: {
      defaultValue: props.defaultValue,
      value: props.value,
      onChange: props.onChange,
      disabled: isDisabled,
      readOnly: isReadOnly,
      required: isRequired,
      "aria-required": isRequired === true ? true : undefined,
      "aria-invalid": props.isInvalid,
      "aria-describedby": ariaDescribedBy,
      "aria-errormessage": props["aria-errormessage"],
      role: props.role,

      type: inputElementType === "input" ? props.type : undefined,
      pattern: inputElementType === "input" ? props.pattern : undefined,

      autoComplete: props.autoComplete,
      maxLength: props.maxLength,
      minLength: props.minLength,
      name: props.name,
      placeholder: props.placeholder,
      inputMode: props.inputMode,

      // Clipboard events
      onCopy: props.onCopy,
      onCut: props.onCut,
      onPaste: props.onPaste,

      // Composition events
      onCompositionEnd: props.onCompositionEnd,
      onCompositionStart: props.onCompositionStart,
      onCompositionUpdate: props.onCompositionUpdate,

      // Selection events
      onSelect: props.onSelect,

      // Input events
      onBeforeInput: props.onBeforeInput,
      onInput: props.onInput,

      // Focus events
      onFocus: props.onFocus,
      onBlur: props.onBlur,

      ...fieldProps,
    },
  };
}
