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

export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  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 Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
  ({ label, hint, error, id, className, required, rows = 5, ...props }, ref) => {
    const autoId = useAutoId("textarea");
    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>
        <textarea
          ref={ref}
          id={inputId}
          rows={rows}
          required={required}
          aria-describedby={cn(hintId, errorId) || undefined}
          aria-invalid={!!error}
          className={cn(
            "resize-y rounded-md border border-line bg-paper px-3.5 py-3 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>
    );
  }
);
Textarea.displayName = "Textarea";
