"use client";

import { forwardRef, type InputHTMLAttributes, type ReactNode } from "react";
import Field from "./Field";

export interface TextFieldProps
  extends Omit<InputHTMLAttributes<HTMLInputElement>, "id" | "className"> {
  id: string;
  label: string;
  error?: string;
  hint?: ReactNode;
  /** Rendered between the control and the hint — e.g. a companion checkbox. */
  footer?: ReactNode;
  /** Uppercases as typed. For document numbers, where the value is uppercase anyway. */
  uppercase?: boolean;
  /**
   * Shows a confirmation tick inside the control. Reserve it for fields that
   * are expensive to re-check (passport number, date of birth) — Baymard found
   * positive validation helps there, and reads as noise everywhere else.
   */
  showValid?: boolean;
  className?: string;
}

/**
 * Text input wired to `Field`. `forwardRef` so React Hook Form's `register()`
 * can be spread straight onto it.
 */
const TextField = forwardRef<HTMLInputElement, TextFieldProps>(function TextField(
  {
    id,
    label,
    error,
    hint,
    footer,
    uppercase,
    showValid,
    required,
    className,
    ...inputProps
  },
  ref
) {
  return (
    <Field
      id={id}
      label={label}
      required={required}
      hint={hint}
      error={error}
      footer={footer}
      className={className}
    >
      {(a11y) => (
        <span className="lf-control-wrap">
          <input
            ref={ref}
            type="text"
            {...a11y}
            {...inputProps}
            className={[
              "lf-control",
              uppercase ? "lf-control--upper" : "",
              error ? "lf-control--invalid" : "",
              showValid ? "lf-control--checked" : "",
            ]
              .filter(Boolean)
              .join(" ")}
          />
          {showValid ? (
            <svg className="lf-tick" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path
                d="m3 8.5 3.4 3.4L13 5.3"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          ) : null}
        </span>
      )}
    </Field>
  );
});

export default TextField;
