import type { AuthUser } from "../../types";
import { api } from "../../services/api";
import { setSession } from "../../services/authState";
import { notify, notifyError } from "../../ui/dialogs";
import "./login.css";

export function renderLogin(onSuccess: () => Promise<void> | void) {
  document.querySelector<HTMLDivElement>("#app")!.innerHTML = `
    <main class="login-shell">
      <section class="login-panel">
        <div>
          <h1>DMT 模型库</h1>
          <p>模型文件、目录和属性维护</p>
        </div>
        <form id="loginForm" class="form-stack">
          <label>
            <span>用户名</span>
            <input name="username" autocomplete="username" value="admin" />
          </label>
          <label>
            <span>密码</span>
            <input name="password" type="password" autocomplete="current-password" value="admin123" />
          </label>
          <label>
            <span>图片验证码</span>
            <div class="captcha-row">
              <input name="captcha" value="1234" />
              <button type="button" class="captcha-box">1234</button>
            </div>
          </label>
          <button class="primary-btn" type="submit">登录</button>
          <button class="ghost-btn" id="registerBtn" type="button">注册普通账号</button>
          <p id="loginMessage" class="message"></p>
        </form>
      </section>
    </main>
  `;

  document.querySelector<HTMLFormElement>("#loginForm")!.addEventListener("submit", async (event) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget as HTMLFormElement);
    try {
      const result = await api<{ token: string; user: AuthUser }>("/api/auth/login", {
        method: "POST",
        body: JSON.stringify({
          username: form.get("username"),
          password: form.get("password"),
          captcha: form.get("captcha")
        })
      });
      setSession(result.token, result.user);
      await onSuccess();
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      document.querySelector("#loginMessage")!.textContent = message;
    }
  });

  document.querySelector<HTMLButtonElement>("#registerBtn")!.addEventListener("click", async () => {
    const form = new FormData(document.querySelector<HTMLFormElement>("#loginForm")!);
    try {
      await api("/api/auth/register", {
        method: "POST",
        body: JSON.stringify({
          username: form.get("username"),
          password: form.get("password"),
          captcha: form.get("captcha")
        })
      });
      notify("注册成功，可以登录");
    } catch (error) {
      notifyError(error);
    }
  });
}

