"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";
import Link from "next/link";

interface PlatformUser {
  uid: string;
  username: string;
  display_name: string | null;
  avatar_url: string | null;
  organization: string | null;
  last_sign_in_at: string | null;
  created_at: string;
  is_active: boolean;
  email?: string;
}

export default function PlatformUsersPage() {
  const [users, setUsers] = useState<PlatformUser[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [batchLoading, setBatchLoading] = useState(false);
  const [editUser, setEditUser] = useState<PlatformUser | null>(null);
  const [editForm, setEditForm] = useState({ email: "", password: "", displayName: "", organization: "" });
  const [editLoading, setEditLoading] = useState(false);
  const [editMsg, setEditMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const pageSize = 20;

  useEffect(() => { loadUsers(); }, [page, search]);
  async function loadUsers() {
    setLoading(true);
    setSelected(new Set());
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (search) params.set("search", search);
    const res = await fetch(`/api/platform/users?${params}`);
    const data = await res.json();
    setUsers(data.users || []);
    setTotal(data.total || 0);
    setLoading(false);
  }

  function toggleAll() {
    if (selected.size === users.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(users.map((u) => u.uid)));
    }
  }

  function toggle(uid: string) {
    const next = new Set(selected);
    if (next.has(uid)) next.delete(uid);
    else next.add(uid);
    setSelected(next);
  }

  async function handleBatchAction(action: "enable" | "disable") {
    if (selected.size === 0) return;
    if (!confirm(`${action === "enable" ? "启用" : "禁用"} ${selected.size} 个用户？`)) return;
    setBatchLoading(true);
    try {
      const res = await fetch("/api/platform/users", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: Array.from(selected), action }),
      });
      const data = await res.json();
      if (res.ok) {
        setSelected(new Set());
        loadUsers();
      } else {
        alert(data.error || "批量操作失败");
      }
    } catch {
      alert("批量操作失败");
    } finally {
      setBatchLoading(false);
    }
  }

  async function openEdit(u: PlatformUser) {
    setEditUser(u);
    setEditForm({ email: "", password: "", displayName: u.display_name || "", organization: u.organization || "" });
    setEditMsg(null);
    // 如果当前用户列表没有 email，去 API 获取
    if (!u.email) {
      try {
        const res = await fetch(`/api/platform/users/${u.uid}`);
        const data = await res.json();
        if (data.user?.email) {
          setEditForm(f => ({ ...f, email: data.user.email }));
        }
      } catch {}
    } else {
      setEditForm(f => ({ ...f, email: u.email || "" }));
    }
  }

  async function handleEdit() {
    if (!editUser) return;
    setEditLoading(true);
    setEditMsg(null);
    try {
      const body: Record<string, string | undefined> = {};
      if (editForm.email !== undefined) body.email = editForm.email;
      if (editForm.password) body.password = editForm.password;
      if (editForm.displayName !== (editUser.display_name ?? "")) {
        body.displayName = editForm.displayName || undefined;
      }
      if (editForm.organization !== (editUser.organization ?? "")) {
        body.organization = editForm.organization || undefined;
      }
      const res = await fetch(`/api/platform/users/${editUser.uid}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) {
        setEditMsg({ type: "error", text: data.error || "保存失败" });
        return;
      }
      setEditMsg({ type: "success", text: "保存成功" });
      setTimeout(() => { setEditUser(null); loadUsers(); }, 1000);
    } catch {
      setEditMsg({ type: "error", text: "保存失败" });
    } finally {
      setEditLoading(false);
    }
  }

  const totalPages = Math.ceil(total / pageSize);
  const allSelected = users.length > 0 && selected.size === users.length;

  return (
    <div className="admin-content">
      <div className="page-header">
        <h1 className="page-title">平台用户管理</h1>
        <p className="page-subtitle">共 {total} 个平台用户</p>
      </div>
      <div className="toolbar">
        <input type="text" className="form-input search-input" placeholder="搜索用户名或显示名..."
          value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }} />
        {selected.size > 0 && (
          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
            <span style={{ fontSize: "13px", color: "#737373" }}>已选 {selected.size} 个</span>
            <button className="btn btn-primary btn-sm" disabled={batchLoading}
              onClick={() => handleBatchAction("enable")}>
              {batchLoading ? "处理中..." : "批量启用"}
            </button>
            <button className="btn btn-danger btn-sm" disabled={batchLoading}
              onClick={() => handleBatchAction("disable")}>
              {batchLoading ? "处理中..." : "批量禁用"}
            </button>
          </div>
        )}
      </div>
      <div className="card">
        {loading ? <div className="loading">加载中...</div> : (
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th style={{ width: "36px" }}>
                    <input type="checkbox" checked={allSelected} onChange={toggleAll} />
                  </th>
                  <th>用户名</th><th>显示名</th><th>状态</th><th>组织</th>
                  <th>注册时间</th><th>最后登录</th><th>操作</th>
                </tr>
              </thead>
              <tbody>
                {users.map((u) => (
                  <tr key={u.uid}>
                    <td>
                      <input type="checkbox" checked={selected.has(u.uid)} onChange={() => toggle(u.uid)} />
                    </td>
                    <td>{u.username}</td>
                    <td>{u.display_name || "-"}</td>
                    <td>
                      <span className={`badge ${u.is_active ? "badge-success" : "badge-danger"}`}>
                        {u.is_active ? "正常" : "禁用"}
                      </span>
                    </td>
                    <td>{u.organization || "-"}</td>
                    <td>{format(new Date(u.created_at), "yyyy-MM-dd")}</td>
                    <td>{u.last_sign_in_at ? format(new Date(u.last_sign_in_at), "yyyy-MM-dd HH:mm") : "从未登录"}</td>
                    <td><button className="btn btn-secondary btn-sm" onClick={() => openEdit(u)}>编辑</button></td>
                  </tr>
                ))}
                {users.length === 0 && (
                  <tr><td colSpan={8} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无数据</td></tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>
      {totalPages > 1 && (
        <div className="pagination">
          <span className="pagination-info">第 {page} / {totalPages} 页，共 {total} 条</span>
          <button className="btn btn-secondary btn-sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>上一页</button>
          <button className="btn btn-secondary btn-sm" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>下一页</button>
        </div>
      )}

      {editUser && (
        <div className="modal-overlay" onClick={() => setEditUser(null)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: "480px" }}>
            <h2 className="modal-title">编辑用户 — {editUser.username}</h2>
            <div style={{ fontSize: "13px", color: "#737373", marginBottom: "16px" }}>
              UID: <code>{editUser.uid}</code>
            </div>
            {editMsg && (
              <div className={`alert ${editMsg.type === "error" ? "alert-error" : "alert-success"}`} style={{ marginBottom: "12px" }}>
                {editMsg.text}
              </div>
            )}
            <div className="form-group">
              <label className="form-label">邮箱</label>
              <input className="form-input" type="email" value={editForm.email}
                onChange={e => setEditForm(f => ({ ...f, email: e.target.value }))}
                placeholder="user@example.com" />
            </div>
            <div className="form-group">
              <label className="form-label">新密码（留空则不修改）</label>
              <input className="form-input" type="password" value={editForm.password}
                onChange={e => setEditForm(f => ({ ...f, password: e.target.value }))}
                placeholder="至少6位" minLength={6} />
            </div>
            <div className="form-group">
              <label className="form-label">显示名</label>
              <input className="form-input" value={editForm.displayName}
                onChange={e => setEditForm(f => ({ ...f, displayName: e.target.value }))}
                placeholder="可选" />
            </div>
            <div className="form-group">
              <label className="form-label">组织</label>
              <input className="form-input" value={editForm.organization}
                onChange={e => setEditForm(f => ({ ...f, organization: e.target.value }))}
                placeholder="可选" />
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary" onClick={() => setEditUser(null)}>取消</button>
              <button className="btn btn-primary" disabled={editLoading} onClick={handleEdit}>
                {editLoading ? "保存中..." : "保存"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
