/* global React, Icon, SEED_USERS */

const { useState, useEffect, useRef } = React;

const LoginPage = ({ users, successBanner, onLoginSuccess, onForceChangePassword }) => {
  const [email, setEmail]       = useState("");
  const [password, setPassword] = useState("");
  const [showPw, setShowPw]     = useState(false);
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState(null); // { field: "email"|"password"|"both", msg: string }

  const canSubmit = email.trim().length > 0 && password.length > 0 && !loading;

  const handleSubmit = () => {
    if (!canSubmit) return;
    setLoading(true);
    setError(null);
    setTimeout(() => {
      setLoading(false);
      const user = users.find(u => u.email === email.trim().toLowerCase());
      if (!user) {
        setError({ field: "email", msg: "找不到此帳號，請確認 Email 是否正確" });
        return;
      }
      if (user.status === "disabled") {
        setError({ field: "email", msg: "此帳號已停用，請聯絡系統管理員" });
        return;
      }
      if (user.password !== password) {
        setError({ field: "password", msg: "密碼錯誤，請重新輸入" });
        return;
      }
      if (user.mustChangePassword) {
        onForceChangePassword(user);
      } else {
        onLoginSuccess(user);
      }
    }, 800);
  };

  const onKeyDown = (e) => { if (e.key === "Enter") handleSubmit(); };

  return (
    <div className="auth-screen">
      <div className="auth-card">
        <div className="auth-logo">
          <div className="auth-logo__icon">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 2L2 7l10 5 10-5-10-5z"/>
              <path d="M2 17l10 5 10-5"/>
              <path d="M2 12l10 5 10-5"/>
            </svg>
          </div>
          <div>
            <div className="auth-logo__name">DG SKU 管理系統</div>
            <div className="auth-logo__sub">Uber Eats Taiwan</div>
          </div>
        </div>

        <div className="auth-title">登入帳號</div>
        <div className="auth-subtitle">使用您的企業 Email 登入</div>

        {successBanner && (
          <div className="auth-success-banner">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="20 6 9 17 4 12"/>
            </svg>
            密碼已設定完成，請重新登入
          </div>
        )}

        <div className="auth-field">
          <label className="auth-field__label">Email</label>
          <input
            type="email"
            className={"auth-field__input" + (error?.field === "email" ? " auth-field__input--error" : "")}
            placeholder="請輸入 Email"
            value={email}
            onChange={e => { setEmail(e.target.value); setError(null); }}
            onKeyDown={onKeyDown}
            disabled={loading}
            autoComplete="email"
          />
          {error?.field === "email" && (
            <div className="auth-field__error">
              <Icon name="alertCircle" size={13} />
              {error.msg}
            </div>
          )}
        </div>

        <div className="auth-field" style={{ marginTop: 12 }}>
          <label className="auth-field__label">密碼</label>
          <div className="auth-field__input-wrap">
            <input
              type={showPw ? "text" : "password"}
              className={"auth-field__input auth-field__input--pw" + (error?.field === "password" ? " auth-field__input--error" : "")}
              placeholder="請輸入密碼"
              value={password}
              onChange={e => { setPassword(e.target.value); setError(null); }}
              onKeyDown={onKeyDown}
              disabled={loading}
              autoComplete="current-password"
            />
            <button className="auth-field__pw-toggle" onClick={() => setShowPw(v => !v)} tabIndex={-1} type="button">
              {showPw
                ? <Icon name="eye" size={16} />
                : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
              }
            </button>
          </div>
          {error?.field === "password" && (
            <div className="auth-field__error">
              <Icon name="alertCircle" size={13} />
              {error.msg}
            </div>
          )}
        </div>

        <button
          className={"auth-submit-btn" + (loading ? " auth-submit-btn--loading" : "")}
          disabled={!canSubmit}
          onClick={handleSubmit}
        >
          {loading ? (
            <><span className="auth-spinner"/><span>驗證中...</span></>
          ) : "登入"}
        </button>
      </div>
    </div>
  );
};

Object.assign(window, { LoginPage });
