"use client";

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

interface Workspace {
  id: string;
  slug: string;
  name: string;
  plan: string;
  description: string | null;
  billing_email: string | null;
  balance: string | null;
  currency: string | null;
  member_count: number;
  project_count: number;
  created_at: string;
}

const PLAN_LABELS: Record<string, string> = {
  free: "免费", starter: "入门", pro: "专业", enterprise: "企业",
};

const ALL_PLANS = ["free", "starter", "pro", "enterprise"];

export default function WorkspacesPage() {
  const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [plan, setPlan] = useState("");
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [batchPlan, setBatchPlan] = useState("");
  const [batchLoading, setBatchLoading] = useState(false);
  const pageSize = 20;

  useEffect(() => { loadWorkspaces(); }, [page, search, plan]);

  function loadWorkspaces() {
    setLoading(true);
    setSelected(new Set());
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (search) params.set("search", search);
    if (plan) params.set("plan", plan);
    fetch(`/api/platform/workspaces?${params}`)
      .then((r) => r.json())
      .then((data) => {
        setWorkspaces(data.workspaces || []);
        setTotal(data.total || 0);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }

  function toggleAll() {
    if (selected.size === workspaces.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(workspaces.map((w) => w.id)));
    }
  }

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

  async function handleBatchPlanChange() {
    if (!batchPlan || selected.size === 0) return;
    if (!confirm(`将 ${selected.size} 个 Workspace 调整为「${PLAN_LABELS[batchPlan] || batchPlan}」？`)) return;
    setBatchLoading(true);
    try {
      const res = await fetch("/api/platform/workspaces", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ids: Array.from(selected), plan: batchPlan }),
      });
      const data = await res.json();
      if (res.ok) {
        setSelected(new Set());
        setBatchPlan("");
        loadWorkspaces();
      } else {
        alert(data.error || "批量调整失败");
      }
    } catch (e) {
      alert("批量调整失败");
    } finally {
      setBatchLoading(false);
    }
  }

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

  return (
    <div className="admin-content">
      <div className="page-header">
        <h1 className="page-title">Workspace 管理</h1>
        <p className="page-subtitle">共 {total} 个 Workspace</p>
      </div>
      <div className="toolbar">
        <input
          type="text" className="form-input search-input"
          placeholder="搜索名称或 slug..."
          value={search} onChange={(e) => { setSearch(e.target.value); setPage(1); }}
        />
        <select className="form-input" style={{ maxWidth: "160px" }}
          value={plan} onChange={(e) => { setPlan(e.target.value); setPage(1); }}>
          <option value="">全部计划</option>
          {Object.entries(PLAN_LABELS).map(([k, v]) => (
            <option key={k} value={k}>{v}</option>
          ))}
        </select>
        {selected.size > 0 && (
          <div style={{ display: "flex", alignItems: "center", gap: "8px", marginLeft: "8px" }}>
            <span style={{ fontSize: "13px", color: "#737373" }}>已选 {selected.size} 个</span>
            <select className="form-input" style={{ maxWidth: "120px" }}
              value={batchPlan} onChange={(e) => setBatchPlan(e.target.value)}>
              <option value="">选择计划</option>
              {ALL_PLANS.map((p) => (
                <option key={p} value={p}>{PLAN_LABELS[p]}</option>
              ))}
            </select>
            <button className="btn btn-primary btn-sm" disabled={!batchPlan || batchLoading}
              onClick={handleBatchPlanChange}>
              {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>Slug</th><th>计划</th>
                  <th>余额</th><th>成员</th><th>项目</th><th>创建时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {workspaces.map((w) => (
                  <tr key={w.id}>
                    <td>
                      <input type="checkbox" checked={selected.has(w.id)} onChange={() => toggle(w.id)} />
                    </td>
                    <td>{w.name}</td>
                    <td><code style={{ fontSize: "12px" }}>{w.slug}</code></td>
                    <td><span className="badge badge-neutral">{PLAN_LABELS[w.plan] || w.plan}</span></td>
                    <td>
                      {w.balance
                        ? `${parseFloat(w.balance).toFixed(2)} ${w.currency || "USD"}`
                        : "-"}
                    </td>
                    <td>{w.member_count}</td>
                    <td>{w.project_count}</td>
                    <td>{format(new Date(w.created_at), "yyyy-MM-dd")}</td>
                    <td>
                      <Link href={`/admin/workspaces/${w.id}`}>
                        <button className="btn btn-secondary btn-sm">详情</button>
                      </Link>
                    </td>
                  </tr>
                ))}
                {workspaces.length === 0 && (
                  <tr><td colSpan={9} 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>
      )}
    </div>
  );
}
