import { useEffect, useRef, useState } from "react";
import type { FormEvent } from "react";
import { api } from "../api";
import type { Team, User } from "../types";
import type { AuthMode } from "./route-config";

const CHECK_SVG = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
);
const MAIL_SVG = (
  <svg className="ic-l" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z" /><path d="m22 6-10 7L2 6" /></svg>
);
const LOCK_SVG = (
  <svg className="ic-l" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>
);
const EYE_SVG = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z" /><circle cx="12" cy="12" r="3" /></svg>
);
const ARROW_SVG = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7" /></svg>
);

export function AuthScreen({
  initialMode,
  onModeChange,
  onAuthed
}: {
  initialMode: AuthMode;
  onModeChange: (mode: AuthMode) => void;
  onAuthed: (payload: { token: string; user: User; team: Team }) => void;
}) {
  const [mode, setMode] = useState<AuthMode>(initialMode);
  const [username, setUsername] = useState("li@shop.com");
  const [password, setPassword] = useState("demo-1234");
  const [teamName, setTeamName] = useState("");
  const [email, setEmail] = useState("");
  const [registerPassword, setRegisterPassword] = useState("");
  const [registerPassword2, setRegisterPassword2] = useState("");
  const [invite, setInvite] = useState("");
  const [agreed, setAgreed] = useState(true);
  const [showPwd, setShowPwd] = useState(false);
  const [showRegPwd, setShowRegPwd] = useState(false);
  const [showRegPwd2, setShowRegPwd2] = useState(false);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [toast, setToast] = useState<{ title: string; sub: string } | null>(null);
  const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => setMode(initialMode), [initialMode]);
  useEffect(() => () => { if (toastTimer.current) clearTimeout(toastTimer.current); }, []);

  function showToast(title: string, sub: string) {
    setToast({ title, sub });
    if (toastTimer.current) clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 2800);
  }

  function switchMode(next: AuthMode) {
    setMode(next);
    setError("");
    onModeChange(next);
  }

  async function submit(event: FormEvent) {
    event.preventDefault();
    setBusy(true);
    setError("");
    try {
      if (mode === "register") {
        if (registerPassword.length < 8) throw new Error("密码至少 8 位");
        if (registerPassword !== registerPassword2) throw new Error("两次密码不一致");
        if (!agreed) throw new Error("请同意用户协议");
      }
      const payload =
        mode === "login"
          ? await api.login({ username, password })
          : await api.register({
              username: email,
              email,
              password: registerPassword,
              team_name: teamName
            });
      onAuthed(payload);
    } catch (err) {
      setError(err instanceof Error ? err.message : "登录失败");
    } finally {
      setBusy(false);
    }
  }

  return (
    <main className={`auth-exact-page ${mode === "register" ? "auth-register-page" : "auth-login-page"}`}>
      <a className="top-back" href={mode === "register" ? "/login" : "/dashboard"} onClick={(event) => { if (mode === "register") { event.preventDefault(); switchMode("login"); } }}>
        {mode === "register" ? "← 返回登录" : "← 返回工作台"}
      </a>
      <div className="auth-wrap">
        <span className="corner-tr" aria-hidden="true"></span><span className="corner-bl" aria-hidden="true"></span>
        <aside className="auth-brand">
          <div className="logo"><img className="logo-img" src="/assets/logo-dark.png" alt="Airshelf" /></div>
          <div className="tag">// SHORT-VIDEO COMMERCE PLATFORM</div>
          <div className="hero">
            {mode === "login" ? <><h1>AI 全流程<br /><span className="h">短剧化</span>带货生成</h1><p>商品 → AI 脚本 → 故事板 → Seedance 视频片段 → 一键导出 9:16 ≤60s 成片。</p></> : <><h1>开通团队,<br />开始 <span className="h">AI 带货</span> 第一条短剧</h1><p>个人 / 企业团队 1-2 小时出成片,失败不扣费,确认后扣。</p></>}
          </div>
          {mode === "login" ? (
            <div className="ascii">
              <div className="ln"><span className="k">// step·1</span> &nbsp; 脚本生成 &nbsp; &nbsp; <span className="v">●●●●●</span></div>
              <div className="ln"><span className="k">// step·2</span> &nbsp; 基础资产 &nbsp; &nbsp; <span className="v">●●●●○</span></div>
              <div className="ln"><span className="k">// step·3</span> &nbsp; 故事板 &nbsp; &nbsp; &nbsp; <span className="v">●●●○○</span></div>
              <div className="ln"><span className="k">// step·4</span> &nbsp; 视频片段 &nbsp; &nbsp; <span className="v">●●○○○</span></div>
              <div className="ln"><span className="k">// step·5</span> &nbsp; 拼接导出 &nbsp; &nbsp; <span className="v">●○○○○</span></div>
            </div>
          ) : (
            <div className="val-list">
              <div className="val-item"><span className="ic-v">{CHECK_SVG}</span><span className="txt-v"><b>5 阶段流水线</b> · 脚本 → 资产 → 故事板 → 视频片段 → 拼接导出</span></div>
              <div className="val-item"><span className="ic-v">{CHECK_SVG}</span><span className="txt-v"><b>失败不扣费</b> · 任务仅在用户通过时扣费,失败 / 超时 / 重跑一律不扣</span></div>
              <div className="val-item"><span className="ic-v">{CHECK_SVG}</span><span className="txt-v"><b>团队 + 角色 + 四层额度</b> · 超管 / 团管 / 成员,日 / 月 + 团队 / 总四层防超支</span></div>
              <div className="val-item"><span className="ic-v">{CHECK_SVG}</span><span className="txt-v"><b>跨项目资产库</b> · 主播 / 场景 / 商品图沉淀复用,不重复生成</span></div>
            </div>
          )}
          <div className="foot"><a href="#">关于</a><a href="#">定价</a><a href="#">联系</a><a href="#">隐私</a></div>
        </aside>
        <main className="auth-form">
          <div className="h-row"><h2>{mode === "login" ? "登录" : "注册团队"}</h2><span className="sub">{mode === "login" ? "// /auth/login" : "// /auth/register"}</span></div>
          <p className="lead">{mode === "login" ? "使用团队邀请邮箱登录,接受邀请后自动加入对应团队。" : "填写团队信息开通账户,默认成为团队超管。"}</p>
          {mode === "login" ? (
            <form id="login-form" autoComplete="off" onSubmit={submit}>
              <div className="field">
                <label className="field-label" htmlFor="auth-email">邮箱 <span className="req">*</span></label>
                <div className="field-input-wrap">
                  {MAIL_SVG}
                  <input type="email" id="auth-email" placeholder="name@company.com" value={username} onChange={(event) => setUsername(event.target.value)} required />
                </div>
              </div>
              <div className="field">
                <label className="field-label" htmlFor="auth-pwd">密码 <span className="req">*</span></label>
                <div className="field-input-wrap">
                  {LOCK_SVG}
                  <input type={showPwd ? "text" : "password"} id="auth-pwd" placeholder="••••••••" value={password} onChange={(event) => setPassword(event.target.value)} required />
                  <button type="button" className="toggle-pwd" aria-label="切换密码可见" onClick={() => setShowPwd((value) => !value)}>{EYE_SVG}</button>
                </div>
              </div>
              <div className="row-between">
                <label><input type="checkbox" defaultChecked /> 记住我 7 天</label>
                <a href="#" onClick={(event) => { event.preventDefault(); showToast("已发送重置邮件", "请到 li@shop.com 收件箱查看 · 链接 30 分钟有效"); }}>忘记密码?</a>
              </div>
              {error && <div className="form-error">{error}</div>}
              <button className="btn-cta" type="submit" disabled={busy}>
                {busy ? <span className="busy-copy">// 验证中...</span> : <>登录{ARROW_SVG}</>}
              </button>
              <div className="divider"><span className="line"></span><span className="txt">OR</span><span className="line"></span></div>
              <div className="sso-row">
                <button type="button" className="sso-btn" onClick={() => showToast("微信扫码", "请在 60s 内用微信扫一扫完成授权 · 内测中,以邮箱登录为准")}>
                  <svg viewBox="0 0 24 24" fill="currentColor"><path d="M9 4C5 4 2 6.5 2 9.5c0 1.7 1 3.2 2.5 4.2L4 16l2.2-1.1c.7.2 1.5.3 2.3.3-.3-.5-.5-1.1-.5-1.7 0-2.8 2.9-5 6.5-5h.5C14.6 6 12 4 9 4zm-2 3.5c.6 0 1 .4 1 1s-.4 1-1 1-1-.4-1-1 .4-1 1-1zm4 0c.6 0 1 .4 1 1s-.4 1-1 1-1-.4-1-1 .4-1 1-1zM15 9c-3.3 0-6 2.2-6 5s2.7 5 6 5c.7 0 1.4-.1 2-.3L19 20l-.4-1.7c1.4-.9 2.4-2.3 2.4-3.8 0-2.8-2.7-5-6-5zm-2 2.5c.6 0 1 .4 1 1s-.4 1-1 1-1-.4-1-1 .4-1 1-1zm4 0c.6 0 1 .4 1 1s-.4 1-1 1-1-.4-1-1 .4-1 1-1z" /></svg>
                  微信扫码
                </button>
                <button type="button" className="sso-btn" onClick={() => showToast("飞书 SSO", "即将打开企业飞书登录授权页 · 内测中,以邮箱登录为准")}>
                  <svg viewBox="0 0 24 24" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="3" /></svg>
                  飞书 SSO
                </button>
              </div>
              <div className="switch-row">还没账号? <a href="/register" onClick={(event) => { event.preventDefault(); switchMode("register"); }}>注册团队 →</a></div>
            </form>
          ) : (
            <form id="register-form" autoComplete="off" onSubmit={submit}>
              <div className="field">
                <label className="field-label" htmlFor="reg-team">团队名 <span className="req">*</span></label>
                <div className="field-input-wrap">
                  <svg className="ic-l" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /><path d="M9 22V12h6v10" /></svg>
                  <input type="text" id="reg-team" placeholder="例: 小李的店 / XX 文化传媒" value={teamName} onChange={(event) => setTeamName(event.target.value)} required />
                </div>
              </div>
              <div className="field">
                <label className="field-label" htmlFor="reg-email">超管邮箱 <span className="req">*</span><span className="hint">用于成员邀请 + 找回密码</span></label>
                <div className="field-input-wrap">
                  {MAIL_SVG}
                  <input type="email" id="reg-email" placeholder="name@company.com" value={email} onChange={(event) => setEmail(event.target.value)} required />
                </div>
              </div>
              <div className="field-row">
                <div className="field">
                  <label className="field-label" htmlFor="reg-pwd">密码 <span className="req">*</span></label>
                  <div className="field-input-wrap">
                    {LOCK_SVG}
                    <input type={showRegPwd ? "text" : "password"} id="reg-pwd" placeholder="至少 8 位" value={registerPassword} onChange={(event) => setRegisterPassword(event.target.value)} required />
                    <button type="button" className="toggle-pwd" onClick={() => setShowRegPwd((value) => !value)}>{EYE_SVG}</button>
                  </div>
                </div>
                <div className="field">
                  <label className="field-label" htmlFor="reg-pwd2">确认密码 <span className="req">*</span></label>
                  <div className="field-input-wrap">
                    {LOCK_SVG}
                    <input type={showRegPwd2 ? "text" : "password"} id="reg-pwd2" placeholder="再输一次" value={registerPassword2} onChange={(event) => setRegisterPassword2(event.target.value)} required />
                    <button type="button" className="toggle-pwd" onClick={() => setShowRegPwd2((value) => !value)}>{EYE_SVG}</button>
                  </div>
                </div>
              </div>
              <div className="field">
                <label className="field-label" htmlFor="reg-invite">邀请码 <span className="hint">可选 · 团队邀请才需要</span></label>
                <div className="field-input-wrap">
                  <svg className="ic-l" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /></svg>
                  <input type="text" id="reg-invite" placeholder="例: TEAM-XXXX-XXXX" value={invite} onChange={(event) => setInvite(event.target.value)} />
                </div>
              </div>
              <label className="agree">
                <input type="checkbox" id="reg-agree" checked={agreed} onChange={(event) => setAgreed(event.target.checked)} />
                <span>我已阅读并同意 <a href="#" onClick={(event) => { event.preventDefault(); showToast("用户协议", "含数据处理 / 内容生成版权 / 计费规则三章 · 完整文本将在正式版接入"); }}>用户协议</a> 与 <a href="#" onClick={(event) => { event.preventDefault(); showToast("隐私政策", "遵循《个人信息保护法》· 团队数据存中国境内 · 默认不用于模型训练"); }}>隐私政策</a>,知悉「失败不扣费 · 确认后扣」的扣费规则。</span>
              </label>
              {error && <div className="form-error">{error}</div>}
              <button className="btn-cta" type="submit" id="reg-submit" disabled={busy}>
                {busy ? <span className="busy-copy">// 创建团队中...</span> : <>创建团队 · 开始使用{ARROW_SVG}</>}
              </button>
              <div className="switch-row">已有账号? <a href="/login" onClick={(event) => { event.preventDefault(); switchMode("login"); }}>登录 →</a></div>
            </form>
          )}
        </main>
      </div>
      {toast && <div className="login-toast"><div>{toast.title}</div><div style={{ fontSize: "11.5px", color: "rgba(0,0,0,.56)", fontWeight: 400, letterSpacing: ".02em" }}>// {toast.sub}</div></div>}
    </main>
  );
}
