"use client"
import { Text, TextField } from "react-aria-components"
import { Controller, useFormContext } from "react-hook-form"
import { useIntl } from "react-intl"

import { CheckIcon, InfoCircleIcon } from "@/components/Icons"
import AriaInputWithLabel from "@/components/TempDesignSystem/Form/Input/AriaInputWithLabel"
import Caption from "@/components/TempDesignSystem/Text/Caption"

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

import type { HTMLAttributes, WheelEvent } from "react"

import type { InputProps } from "./input"

export default function Input({
  "aria-label": ariaLabel,
  className = "",
  disabled = false,
  helpText = "",
  label,
  maxLength,
  name,
  placeholder = "",
  readOnly = false,
  registerOptions = {},
  type = "text",
}: InputProps) {
  const intl = useIntl()
  const { control } = useFormContext()
  let numberAttributes: HTMLAttributes<HTMLInputElement> = {}
  if (type === "number") {
    numberAttributes.onWheel = function (evt: WheelEvent<HTMLInputElement>) {
      evt.currentTarget.blur()
    }
  }

  return (
    <Controller
      disabled={disabled}
      control={control}
      name={name}
      rules={registerOptions}
      render={({ field, fieldState }) => (
        <TextField
          aria-label={ariaLabel}
          className={className}
          isDisabled={field.disabled}
          isInvalid={fieldState.invalid}
          isRequired={!!registerOptions.required}
          name={field.name}
          onBlur={field.onBlur}
          onChange={field.onChange}
          validationBehavior="aria"
          value={field.value}
        >
          <AriaInputWithLabel
            {...field}
            aria-labelledby={field.name}
            id={field.name}
            label={label}
            maxLength={maxLength}
            placeholder={placeholder}
            readOnly={readOnly}
            required={!!registerOptions.required}
            type={type}
          />
          {helpText && !fieldState.error ? (
            <Caption asChild color="black">
              <Text className={styles.helpText} slot="description">
                <CheckIcon height={20} width={30} />
                {helpText}
              </Text>
            </Caption>
          ) : null}
          {fieldState.error ? (
            <Caption className={styles.error} fontOnly>
              <InfoCircleIcon color="red" />
              {intl.formatMessage({ id: fieldState.error.message })}
            </Caption>
          ) : null}
        </TextField>
      )}
    />
  )
}
