"use client";

import { forwardRef, useId, type InputHTMLAttributes, type ReactNode } from "react";
import { Lightbulb } from "lucide-react";
import { cn } from "@/lib/utils";

interface Props extends InputHTMLAttributes<HTMLInputElement> {
  label: string;
  error?: string;
  hint?: string;
  trailing?: ReactNode;
  labelClassName?: string;
}

export const FormField = forwardRef<HTMLInputElement, Props>(function FormField(
  { label, error, hint, trailing, className, labelClassName, id, ...props },
  ref,
) {
  const reactId = useId();
  const inputId = id ?? `f-${reactId}`;
  const descId = error || hint ? `${inputId}-desc` : undefined;

  return (
    <div className="space-y-1.5">
      <label
        htmlFor={inputId}
        className={labelClassName ?? "block text-[length:var(--text-sm)] font-medium capitalize tracking-wide text-slate-500 dark:text-slate-400"}
      >
        {label}
        {props.required && <span className="ms-1 font-bold text-rose-500 dark:text-rose-400">*</span>}
      </label>
      <div className="relative">
        <input
          ref={ref}
          id={inputId}
          aria-invalid={error ? true : undefined}
          aria-describedby={descId}
          className={cn(
            "h-11 w-full rounded-2xl border bg-white px-4 text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-brand-500 focus:shadow-glow-sm dark:bg-slate-900 dark:text-white",
            error
              ? "border-rose-300 dark:border-rose-400/40"
              : "border-slate-200 dark:border-slate-700",
            trailing && "pe-12",
            className,
          )}
          {...props}
        />
        {trailing && (
          <div className="absolute end-2 top-1/2 -translate-y-1/2">{trailing}</div>
        )}
      </div>
      {error ? (
        <p id={descId} className="text-xs font-medium text-rose-600 dark:text-rose-400">
          {error}
        </p>
      ) : hint ? (
        <p
          id={descId}
          className="motion-safe:animate-fade-in flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300/90"
        >
          <Lightbulb className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500 dark:text-amber-400" aria-hidden />
          <span>{hint}</span>
        </p>
      ) : null}
    </div>
  );
});
