"use client"

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

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import Caption from "@/components/TempDesignSystem/Text/Caption"

import { getErrorMessage } from "./errors"

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

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

const Checkbox = forwardRef<
  HTMLInputElement,
  React.PropsWithChildren<CheckboxProps>
>(function Checkbox(
  {
    className = "",
    name,
    children,
    registerOptions,
    hideError,
    topAlign = false,
  },
  ref
) {
  const { control } = useFormContext()
  const { field, fieldState } = useController({
    control,
    name,
    rules: registerOptions,
  })
  const intl = useIntl()

  return (
    <AriaCheckbox
      className={`${styles.container} ${className}`}
      isSelected={field.value}
      onChange={field.onChange}
      data-testid={name}
      isDisabled={registerOptions?.disabled}
      excludeFromTabOrder
    >
      {({ isSelected }) => (
        <>
          <span
            className={`${styles.checkboxContainer} ${topAlign ? styles.topAlign : ""}`}
          >
            <span
              className={styles.checkbox}
              tabIndex={registerOptions?.disabled ? undefined : 0}
              ref={ref}
            >
              {isSelected && (
                <MaterialIcon icon="check" color="Icon/Inverted" />
              )}
            </span>
            {children}
          </span>
          {fieldState.error && !hideError ? (
            <Caption className={styles.error} fontOnly>
              <MaterialIcon icon="info" color="Icon/Interactive/Accent" />
              {getErrorMessage(intl, fieldState.error.message)}
            </Caption>
          ) : null}
        </>
      )}
    </AriaCheckbox>
  )
})

export default Checkbox
