"use client";
/**
 * 通用文本输入框
 *
 * 
 */
import {
  type ChangeEvent,
  type FocusEvent,
  type KeyboardEvent,
  forwardRef,
} from "react";

import styles from "./auth-text-field.module.css";

export interface AuthTextFieldProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  type?: "text" | "email" | "password" | "tel";
  label?: string;
  errorMessage?: string | null;
  autoComplete?: string;
  maxLength?: number;
  disabled?: boolean;
  onSubmit?: () => void;
  onBlur?: (e: FocusEvent<HTMLInputElement>) => void;
}

export const AuthTextField = forwardRef<HTMLInputElement, AuthTextFieldProps>(
  function AuthTextField(
    {
      value,
      onChange,
      placeholder,
      type = "text",
      label,
      errorMessage,
      autoComplete,
      maxLength,
      disabled,
      onSubmit,
      onBlur,
    },
    ref,
  ) {
    return (
      <label className={styles.wrapper}>
        {label ? <span className={styles.label}>{label}</span> : null}
        <input
          ref={ref}
          className={[styles.input, errorMessage ? styles.invalid : ""]
            .filter(Boolean)
            .join(" ")}
          value={value}
          onChange={(e: ChangeEvent<HTMLInputElement>) =>
            onChange(e.target.value)
          }
          placeholder={placeholder}
          type={type}
          autoComplete={autoComplete}
          maxLength={maxLength}
          disabled={disabled}
          onBlur={onBlur}
          onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
            if (e.key === "Enter" && onSubmit) {
              e.preventDefault();
              onSubmit();
            }
          }}
        />
        {errorMessage ? (
          <span className={styles.error}>{errorMessage}</span>
        ) : null}
      </label>
    );
  },
);
