"use client";

import { useId, useState, type InputHTMLAttributes } from "react";

/* A labelled input in the site's form style (.field), with its error under it. */
export function Field({ label, error, hint, password, ...input }: InputHTMLAttributes<HTMLInputElement> & { label: string; error?: string; hint?: string; password?: boolean }) {
  const id = useId();
  const [shown, setShown] = useState(false);
  const errId = `${id}-err`;
  const control = (
    <input
      id={id}
      {...input}
      type={password ? (shown ? "text" : "password") : input.type}
      aria-invalid={error ? true : undefined}
      aria-describedby={error ? errId : hint ? `${id}-hint` : undefined}
    />
  );
  return (
    <div className={`field${error ? " is-invalid" : ""}`}>
      <label htmlFor={id}>{label}</label>
      {password ? (
        <div className="login__pass">
          {control}
          <button type="button" className="login__toggle" aria-pressed={shown} aria-controls={id} onClick={() => setShown(!shown)}>
            {shown ? "Hide" : "Show"}
          </button>
        </div>
      ) : (
        control
      )}
      {hint && !error ? <p className="hub-hint" id={`${id}-hint`}>{hint}</p> : null}
      <p className="field__err" id={errId}>{error ?? ""}</p>
    </div>
  );
}
