import { useId, type ReactNode } from 'react';
import { cx } from './cx';

/** Classes communes aux champs de saisie (Input, Select). */
export const CLASSES_CHAMP =
  'min-h-11 w-full rounded-md border-2 border-bordure bg-surface px-3 py-2 text-texte aria-invalid:border-alerte-texte';

export interface ChampCommun {
  label: string;
  hint?: string | undefined;
  error?: string | undefined;
  /** Mention affichée après le libellé d'un champ obligatoire, par exemple « obligatoire ». */
  requiredLabel?: string | undefined;
}

interface ChampProps extends ChampCommun {
  id: string | undefined;
  required: boolean | undefined;
  children: (attributs: {
    id: string;
    'aria-describedby': string | undefined;
    'aria-invalid': true | undefined;
  }) => ReactNode;
}

/** Libellé, aide et message d'erreur reliés au champ (WCAG 1.3.1, 3.3.1, 3.3.2). */
export function Champ({ id, label, hint, error, required, requiredLabel, children }: ChampProps) {
  const autoId = useId();
  const champId = id ?? autoId;
  const aideId = `${champId}-aide`;
  const erreurId = `${champId}-erreur`;
  const decritPar = cx(hint && aideId, error && erreurId) || undefined;

  return (
    <div className="flex flex-col gap-1">
      <label htmlFor={champId} className="font-semibold text-texte">
        {label}
        {required && requiredLabel ? (
          <span className="font-normal text-texte-doux"> ({requiredLabel})</span>
        ) : null}
      </label>
      {hint ? (
        <p id={aideId} className="text-sm text-texte-doux">
          {hint}
        </p>
      ) : null}
      {children({
        id: champId,
        'aria-describedby': decritPar,
        'aria-invalid': error ? true : undefined,
      })}
      {error ? (
        <p id={erreurId} className="text-sm font-semibold text-alerte-texte">
          {error}
        </p>
      ) : null}
    </div>
  );
}
