"use client"
import { Input as AriaInput, TextField } from "react-aria-components"
import { useController } from "react-hook-form"

import ErrorMessage from "@/components/TempDesignSystem/Form/ErrorMessage"

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

import type { InputProps } from "./input"

export default function Input({
  "aria-label": ariaLabel,
  control,
  disabled,
  name,
  placeholder,
  registerOptions,
  type = "text",
}: InputProps) {
  const { field, fieldState, formState } = useController({
    control,
    name,
    rules: registerOptions,
  })

  return (
    <TextField
      aria-label={ariaLabel}
      defaultValue={field.value}
      isDisabled={disabled ?? field.disabled}
      isInvalid={fieldState.invalid}
      isRequired={!!registerOptions?.required}
      name={field.name}
      onBlur={field.onBlur}
      onChange={field.onChange}
      type={type}
    >
      <AriaInput
        className={styles.input}
        placeholder={placeholder}
        ref={field.ref}
      />
      <ErrorMessage errors={formState.errors} name={name} />
    </TextField>
  )
}
