"use client"

import { forwardRef, useMemo } from "react"

import { FormInput } from "@scandic-hotels/design-system/Form/FormInput"

import { useBookingFlowConfig } from "../../bookingFlowConfig/bookingFlowConfigContext"
import { getErrorMessage } from "./errors"

import type { RegisterOptions } from "react-hook-form"
import type { IntlShape } from "react-intl"

interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  helpText?: string
  label: string
  name: string
  id?: string
  registerOptions?: RegisterOptions
  hideError?: boolean
}

const BookingFlowInput = forwardRef<HTMLInputElement, InputProps>(
  function Input(
    {
      autoComplete,
      className = "",
      disabled = false,
      helpText = "",
      label,
      maxLength,
      name,
      id,
      placeholder,
      readOnly = false,
      registerOptions = {},
      type = "text",
      hideError,
      inputMode,
      ...props
    },
    ref
  ) {
    const config = useBookingFlowConfig()

    // Create error formatter wrapper that uses getErrorMessage with the variant
    const errorFormatter = useMemo(
      () => (intl: IntlShape, errorMessage?: string) =>
        getErrorMessage(intl, config.variant, errorMessage) ?? "",
      [config.variant]
    )

    return (
      <FormInput
        {...props}
        ref={ref}
        autoComplete={autoComplete}
        className={className}
        description={helpText}
        descriptionIcon="check"
        disabled={disabled}
        errorFormatter={errorFormatter}
        hideError={hideError}
        inputMode={inputMode}
        label={label}
        maxLength={maxLength}
        id={id}
        name={name}
        placeholder={placeholder}
        readOnly={readOnly}
        registerOptions={registerOptions}
        type={type}
      />
    )
  }
)

export default BookingFlowInput
