"use client"

import { forwardRef } from "react"
import { Text, TextField } from "react-aria-components"
import { Controller, useFormContext } from "react-hook-form"
import { useIntl, type IntlShape } from "react-intl"
import { cx } from "class-variance-authority"

import { Error } from "../ErrorMessage/Error"
import { mergeRefs } from "../utils/mergeRefs"
import { TextArea } from "../../TextArea"

import styles from "./textarea.module.css"

import type { FormTextAreaProps } from "./textarea"
import { MaterialIcon, MaterialIconProps } from "../../Icons/MaterialIcon"

const defaultErrorFormatter = (
  _intl: IntlShape,
  errorMessage?: string
): string => errorMessage ?? ""

export const FormTextArea = forwardRef<HTMLTextAreaElement, FormTextAreaProps>(
  function FormTextArea(
    {
      className = "",
      description = "",
      descriptionIcon = "info" as MaterialIconProps["icon"],
      disabled = false,
      errorFormatter,
      hideError,
      label,
      name,
      placeholder,
      readOnly = false,
      registerOptions = {},
      ...props
    },
    ref
  ) {
    const intl = useIntl()
    const { control } = useFormContext()

    const formatErrorMessage = errorFormatter ?? defaultErrorFormatter

    return (
      <Controller
        control={control}
        name={name}
        rules={registerOptions}
        render={({ field, fieldState }) => {
          const isDisabled = disabled || field.disabled
          const hasError = fieldState.invalid && !hideError
          const showDescription = description && !fieldState.error

          return (
            <TextField
              className={cx(styles.wrapper, className)}
              isDisabled={isDisabled}
              isReadOnly={readOnly}
              isInvalid={fieldState.invalid}
            >
              <TextArea
                {...props}
                ref={mergeRefs(field.ref, ref)}
                name={field.name}
                onBlur={field.onBlur}
                onChange={field.onChange}
                value={field.value ?? ""}
                id={field.name}
                label={label}
                placeholder={placeholder}
                readOnly={readOnly}
                disabled={isDisabled}
                required={!!registerOptions.required}
              />
              {showDescription ? (
                <Text className={styles.description} slot="description">
                  <MaterialIcon icon={descriptionIcon} size={20} />
                  {description}
                </Text>
              ) : null}
              {hasError && fieldState.error ? (
                <Text slot="errorMessage" aria-live="polite">
                  <Error>
                    {formatErrorMessage(intl, fieldState.error.message)}
                  </Error>
                </Text>
              ) : null}
            </TextField>
          )
        }}
      />
    )
  }
)

FormTextArea.displayName = "FormTextArea"

// Default export for backwards compatibility
export default FormTextArea
