"use client";

import { forwardRef } from "react";
import type { InputHTMLAttributes } from "react";
import styles from "./FormField.module.css";

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

const FormField = forwardRef<HTMLInputElement, FormFieldProps>(
  ({ label, error, hint, required, id, className = "", ...props }, ref) => {
    const fieldId = id ?? label.toLowerCase().replace(/\s+/g, "-");
    return (
      <div className={`${styles.field} ${error ? styles.hasError : ""}`}>
        <label htmlFor={fieldId} className={styles.label}>
          {label}
          {required && <span className={styles.required} aria-label="wajib">*</span>}
        </label>
        <input
          ref={ref}
          id={fieldId}
          className={`form-control ${className} ${error ? styles.inputError : ""}`}
          aria-describedby={error ? `${fieldId}-error` : hint ? `${fieldId}-hint` : undefined}
          aria-invalid={!!error}
          {...props}
        />
        {hint && !error && (
          <p id={`${fieldId}-hint`} className={styles.hint}>{hint}</p>
        )}
        {error && (
          <p id={`${fieldId}-error`} className={styles.error} role="alert">{error}</p>
        )}
      </div>
    );
  }
);

FormField.displayName = "FormField";
export default FormField;
