"use client";
/**
 * 邮箱登录表单
 */
import { useState } from "react";

import { useAuthDispatch } from "@/stores/auth/auth-context";
import {
  validateEmail,
  validatePassword,
} from "@/app/auth/components/auth-validators";

import { AuthTextField } from "./auth-text-field";
import { AuthPrimaryButton } from "./auth-primary-button";
import { AuthErrorMessage } from "./auth-error-message";
import styles from "./email-form.module.css";
import { AppEnvUtil, Logger } from "@/utils";

const log = new Logger("AppAuthComponentsEmailLoginForm");
const NON_PRODUCTION_DEFAULT_EMAIL = "chanwillian0@gmail.com";
const NON_PRODUCTION_DEFAULT_PASSWORD = "12345678";

export interface EmailLoginFormProps {
  globalError?: string | null;
  isLoading?: boolean;
}

export function EmailLoginForm({
  globalError,
  isLoading,
}: EmailLoginFormProps) {
  const dispatch = useAuthDispatch();
  const [email, setEmail] = useState(() =>
    !AppEnvUtil.isProduction() ? NON_PRODUCTION_DEFAULT_EMAIL : "",
  );
  const [password, setPassword] = useState(() =>
    !AppEnvUtil.isProduction() ? NON_PRODUCTION_DEFAULT_PASSWORD : "",
  );
  // 本地校验错误（client-side）—— 校验失败时展示第一个非 null 的错误
  // 优先级：local validationError > server globalError
  const [validationError, setValidationError] = useState<string | null>(null);

  // 用户在任一字段开始输入 → 清掉旧校验错误（标准 UX：边改边消）
  // 直接在 onChange 调 setState —— React useState 对相同值自动 bail-out 不触发额外渲染
  // 避免 useEffect 内 setState 的"级联渲染"反模式
  const onEmailChange = (v: string) => {
    setEmail(v);
    setValidationError(null);
  };
  const onPasswordChange = (v: string) => {
    setPassword(v);
    setValidationError(null);
  };

  const submit = () => {
    log.debug("[email-login-form] submit ENTRY", {
      emailLength: email.length,
      emailPreview: email.slice(0, 8),
      passwordLength: password.length,
    });
    const emailErr = validateEmail(email);
    const passwordErr = validatePassword(password);
    if (emailErr || passwordErr) {
      const firstErr = emailErr ?? passwordErr ?? null;
      log.warn(
        "[email-login-form] submit VALIDATION FAILED (silent return)",
        { emailErr, passwordErr, surfaced: firstErr },
      );
      setValidationError(firstErr);
      return;
    }
    setValidationError(null);
    log.debug("[email-login-form] submit dispatching AuthEmailLoginSubmitted");
    dispatch({ type: "AuthEmailLoginSubmitted", email, password });
  };

  return (
    <form
      className={styles.form}
      onSubmit={(e) => {
        e.preventDefault();
        submit();
      }}
    >
      <AuthTextField
        type="email"
        value={email}
        onChange={onEmailChange}
        placeholder="Email"
        autoComplete="email"
      />
      <AuthTextField
        type="password"
        value={password}
        onChange={onPasswordChange}
        placeholder="Password"
        autoComplete="current-password"
        onSubmit={submit}
      />
      {/* 优先级：本地校验错误 > 后端 globalError（两个互斥场景：本地校验未过时，UI 不会再有 globalError） */}
      <AuthErrorMessage message={validationError ?? globalError ?? null} />
      <AuthPrimaryButton type="submit" isLoading={isLoading}>
        Login
      </AuthPrimaryButton>
    </form>
  );
}
