"use client";

import classNames from "classnames/dedupe";
import type { RefAttributes } from "react";
import type { UseTextFieldProps } from "../../hooks";
import { useTextField, useValidationClasses } from "../../hooks";
import type { DOMProps } from "../../types/dom";
import { ErrorMessage } from "../ErrorMessage";
import { Label } from "../Label";
import { Stack } from "../Stack";
import { TextAreaInput } from "../TextAreaInput";
import "./TextArea.css";

export type TextAreaElementType = HTMLTextAreaElement;

export interface TextAreaProps
  extends UseTextFieldProps, DOMProps, RefAttributes<TextAreaElementType> {
  className?: string;
  errorMessage?: string;
}

const TextArea = ({ ref, ...props }: TextAreaProps) => {
  const {
    isDisabled,
    className,
    errorMessage,
    label,
    isInvalid,
    ...otherProps
  } = props;

  const { inputProps, labelProps, errorMessageProps } = useTextField(props);

  // Set class name for atom, including interaction state
  const classes = classNames("mobius", "mobius-text-area", className);
  const validationClasses = useValidationClasses({ isInvalid });
  const inputClasses = classNames("mobius-text-area__input", validationClasses);
  const labelClasses = classNames(
    {
      "--is-disabled": isDisabled,
    },
    validationClasses,
  );

  return (
    <Stack className={classes} gap="xs">
      {label && (
        <Label {...labelProps} className={labelClasses}>
          {props.label}
        </Label>
      )}
      <TextAreaInput
        {...otherProps}
        {...inputProps}
        ref={ref}
        className={inputClasses}
        isDisabled={isDisabled}
        aria-invalid={errorMessage != null}
      />
      <ErrorMessage {...errorMessageProps} errorMessage={errorMessage} />
    </Stack>
  );
};

TextArea.displayName = "TextArea";
export { TextArea };
