"use client";

import { FormEvent, useState } from "react";

export default function LoginPage() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [working, setWorking] = useState(false);

  const submit = async (event: FormEvent) => {
    event.preventDefault();
    setError("");
    setWorking(true);
    try {
      const response = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });
      const result = (await response.json()) as { error?: string };
      if (!response.ok) throw new Error(result.error || "登录失败");
      window.location.assign("/");
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "登录失败");
    } finally {
      setWorking(false);
    }
  };

  return (
    <main className="login-page">
      <section className="login-brand">
        <div className="login-logo">K</div>
        <p>KOC LOOP</p>
        <h1>内容分发闭环</h1>
        <span>统一管理内容任务、KOC 发布和数据回收。</span>
      </section>
      <form className="login-card" onSubmit={submit}>
        <p className="eyebrow">后台登录</p>
        <h2>欢迎回来</h2>
        <span className="login-tip">请使用管理员分配的账号和密码</span>
        <label>
          <span>登录账号</span>
          <input
            value={username}
            onChange={(event) => setUsername(event.target.value)}
            autoComplete="username"
            required
          />
        </label>
        <label>
          <span>密码</span>
          <input
            type="password"
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            autoComplete="current-password"
            required
          />
        </label>
        {error && <p className="login-error">{error}</p>}
        <button className="primary-button" disabled={working}>
          {working ? "登录中…" : "登录"}
        </button>
      </form>
    </main>
  );
}
