"use client"

import { Checkbox as AriaCheckbox } from "react-aria-components"
import { useController, useFormContext } from "react-hook-form"

import { InfoCircleIcon } from "@/components/Icons"
import CheckIcon from "@/components/Icons/Check"
import Caption from "@/components/TempDesignSystem/Text/Caption"

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

import type { CheckboxProps } from "@/types/components/checkbox"

export default function Checkbox({
  className,
  name,
  children,
  registerOptions,
  hideError,
}: React.PropsWithChildren<CheckboxProps>) {
  const { control } = useFormContext()
  const { field, fieldState } = useController({
    control,
    name,
    rules: registerOptions,
  })

  return (
    <AriaCheckbox
      className={`${styles.container} ${className}`}
      isSelected={field.value}
      onChange={field.onChange}
      data-testid={name}
      isDisabled={registerOptions?.disabled}
      excludeFromTabOrder
    >
      {({ isSelected }) => (
        <>
          <span className={styles.checkboxContainer}>
            <span
              className={styles.checkbox}
              tabIndex={registerOptions?.disabled ? undefined : 0}
            >
              {isSelected && <CheckIcon color="white" />}
            </span>
            {children}
          </span>
          {fieldState.error && !hideError ? (
            <Caption className={styles.error} fontOnly>
              <InfoCircleIcon color="red" />
              {fieldState.error.message}
            </Caption>
          ) : null}
        </>
      )}
    </AriaCheckbox>
  )
}
