import * as React from "react";
import { cn } from "@/lib/utils";

export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  label: string;
  hint?: string;
  error?: string;
}

let idCounter = 0;
function useAutoId(prefix: string) {
  const ref = React.useRef<string | undefined>(undefined);
  if (!ref.current) ref.current = `${prefix}-${++idCounter}`;
  return ref.current;
}

export const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ label, hint, error, id, className, required, ...props }, ref) => {
    const autoId = useAutoId("input");
    const inputId = id ?? autoId;
    const hintId = hint ? `${inputId}-hint` : undefined;
    const errorId = error ? `${inputId}-error` : undefined;

    return (
      <div className="flex flex-col gap-1.5">
        <label htmlFor={inputId} className="text-label font-medium uppercase text-ink-soft">
          {label}
          {required && <span className="text-primary"> *</span>}
        </label>
        <input
          ref={ref}
          id={inputId}
          required={required}
          aria-describedby={cn(hintId, errorId) || undefined}
          aria-invalid={!!error}
          className={cn(
            "h-11 rounded-md border border-line bg-paper px-3.5 text-body-md text-ink placeholder:text-slate-muted",
            "transition-colors duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30",
            error && "border-error focus:border-error focus:ring-error/30",
            className
          )}
          {...props}
        />
        {hint && !error && (
          <p id={hintId} className="text-caption text-slate">
            {hint}
          </p>
        )}
        {error && (
          <p id={errorId} className="text-caption text-error" role="alert">
            {error}
          </p>
        )}
      </div>
    );
  }
);
Input.displayName = "Input";
