'use client';

import { useId, type ReactNode } from 'react';
import { cn } from '@/lib/cn';

type ControlProps = {
  id: string;
  'aria-describedby'?: string;
  'aria-invalid'?: true;
};

type FormFieldProps = {
  label: string;
  hint?: string;
  optionalLabel?: string;
  error?: string;
  children: (control: ControlProps) => ReactNode;
};

export const inputClass = (invalid: boolean) =>
  cn(
    'min-h-12 w-full rounded-ui border bg-ink px-4 text-base text-bone placeholder:text-mist/60',
    'transition-[border-color,background-color] duration-300 hover:border-line-strong focus:border-gold',
    invalid ? 'border-danger' : 'border-line',
  );

export function FormField({ label, hint, optionalLabel, error, children }: FormFieldProps) {
  const id = useId();
  const hintId = `${id}-hint`;
  const errorId = `${id}-error`;
  const describedBy = [hint && hintId, error && errorId].filter(Boolean).join(' ') || undefined;

  return (
    <div>
      <label htmlFor={id} className="mb-2 flex items-baseline justify-between gap-3 text-sm text-bone">
        <span>{label}</span>
        {optionalLabel && <span className="text-xs text-mist">{optionalLabel}</span>}
      </label>
      {children({ id, 'aria-describedby': describedBy, 'aria-invalid': error ? true : undefined })}
      {hint && !error && (
        <p id={hintId} className="mt-2 text-xs text-mist">
          {hint}
        </p>
      )}
      {error && (
        <p id={errorId} className="mt-2 text-sm text-danger">
          {error}
        </p>
      )}
    </div>
  );
}
