import { InputHTMLAttributes, ReactNode, forwardRef } from "react";
import clsx from "clsx";

export interface FormFieldProps extends InputHTMLAttributes<HTMLInputElement> {
  label: string;
  error?: string;
  hint?: ReactNode;
}

const FormField = forwardRef<HTMLInputElement, FormFieldProps>(
  ({ label, error, hint, id, className, ...rest }, ref) => {
    const fieldId = id ?? rest.name;
    return (
      <label className="flex flex-col gap-1 text-sm" htmlFor={fieldId}>
        <span className="font-medium text-gray-700">{label}</span>
        <input
          ref={ref}
          id={fieldId}
          aria-invalid={Boolean(error)}
          className={clsx(
            "rounded-md border px-3 py-2 text-gray-900 outline-none transition focus:ring-2",
            error
              ? "border-red-400 focus:border-red-500 focus:ring-red-100"
              : "border-gray-300 focus:border-blue-500 focus:ring-blue-100",
            className,
          )}
          {...rest}
        />
        {hint && !error ? (
          <span className="text-xs text-gray-500">{hint}</span>
        ) : null}
        {error ? <span className="text-xs text-red-600">{error}</span> : null}
      </label>
    );
  },
);

FormField.displayName = "FormField";

export default FormField;
