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

import ErrorMessage from "@/components/TempDesignSystem/Form/ErrorMessage"
import Label from "@/components/TempDesignSystem/Form/Label"
import Body from "@/components/TempDesignSystem/Text/Body"

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

import type { InputProps } from "./input"

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

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