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

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,
  ) {
    const inputClassName = [
      "min-h-(--auth-field-height) w-full rounded-full border-0 bg-auth-surface py-0 pl-xxl pr-lg text-(length:--responsive-body) text-auth-text-primary shadow-[0_3px_5px_var(--color-auth-input-shadow)] outline-none transition-shadow duration-150 placeholder:text-auth-input-placeholder focus:shadow-[0_3px_5px_var(--color-auth-input-shadow),0_0_0_2px_var(--color-accent)] disabled:cursor-not-allowed disabled:opacity-70",
      errorMessage
        ? "shadow-[0_3px_5px_rgba(255,77,79,0.18),0_0_0_1px_var(--color-error)] focus:shadow-[0_3px_5px_rgba(255,77,79,0.18),0_0_0_2px_var(--color-error)]"
        : "",
    ]
      .filter(Boolean)
      .join(" ");

    return (
      <label className="flex w-full flex-col gap-xs">
        {label ? (
          <span className="text-(length:--responsive-caption) text-text-secondary">
            {label}
          </span>
        ) : null}
        <input
          ref={ref}
          className={inputClassName}
          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="text-(length:--responsive-caption) text-error">
            {errorMessage}
          </span>
        ) : null}
      </label>
    );
  },
);
