"use client";

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

interface Project {
  id: string;
  name: string;
  display_name: string;
  description: string | null;
  is_public: boolean;
  workspace_id: string | null;
  workspace_name: string | null;
  workspace_slug: string | null;
  balance: string;
  currency: string;
  member_count: number;
  created_at: string;
}

interface Workspace {
  id: string;
  name: string;
  slug: string;
}

export default function ProjectsPage() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [workspaceId, setWorkspaceId] = useState("");
  const [visibility, setVisibility] = useState("");
  const [loading, setLoading] = useState(true);
  const pageSize = 20;

  useEffect(() => {
    fetch("/api/platform/workspaces?pageSize=100")
      .then(r => r.json())
      .then(d => setWorkspaces(d.workspaces || []))
      .catch(console.error);
  }, []);

  useEffect(() => { loadProjects(); }, [page, search, workspaceId, visibility]);

  function loadProjects() {
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (search) params.set("search", search);
    if (workspaceId) params.set("workspaceId", workspaceId);
    if (visibility) params.set("visibility", visibility);
    fetch(`/api/admin/projects?${params}`)
      .then(r => r.json())
      .then(data => {
        setProjects(data.projects || []);
        setTotal(data.total || 0);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }

  const totalPages = Math.ceil(total / pageSize);

  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); }}
        />
        <select className="form-input" style={{ maxWidth: "200px" }}
          value={workspaceId} onChange={e => { setWorkspaceId(e.target.value); setPage(1); }}>
          <option value="">全部 Workspace</option>
          {workspaces.map(w => (
            <option key={w.id} value={w.id}>{w.name}</option>
          ))}
        </select>
        <select className="form-input" style={{ maxWidth: "140px" }}
          value={visibility} onChange={e => { setVisibility(e.target.value); setPage(1); }}>
          <option value="">全部可见性</option>
          <option value="public">公开</option>
          <option value="private">私有</option>
        </select>
      </div>
      <div className="card">
        {loading ? <div className="loading">加载中...</div> : (
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>名称</th>
                  <th>Workspace</th>
                  <th>可见性</th>
                  <th>余额</th>
                  <th>成员</th>
                  <th>创建时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {projects.map(p => (
                  <tr key={p.id}>
                    <td>
                      <div style={{ fontWeight: 500 }}>{p.display_name || p.name}</div>
                      {p.description && <div style={{ fontSize: "12px", color: "#737373" }}>{p.description}</div>}
                    </td>
                    <td>
                      {p.workspace_name
                        ? <span style={{ fontSize: "13px" }}>{p.workspace_name}</span>
                        : <span style={{ color: "#a3a3a3", fontSize: "13px" }}>无</span>
                      }
                    </td>
                    <td>
                      <span className={`badge ${p.is_public ? "badge-success" : "badge-neutral"}`}>
                        {p.is_public ? "公开" : "私有"}
                      </span>
                    </td>
                    <td>
                      {parseFloat(p.balance) > 0
                        ? `${parseFloat(p.balance).toFixed(4)} ${p.currency}`
                        : "—"}
                    </td>
                    <td>{p.member_count}</td>
                    <td>{format(new Date(p.created_at), "yyyy-MM-dd")}</td>
                    <td>
                      <Link href={`/admin/projects/${p.id}`}>
                        <button className="btn btn-secondary btn-sm">详情</button>
                      </Link>
                    </td>
                  </tr>
                ))}
                {projects.length === 0 && (
                  <tr><td colSpan={7} 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>
  );
}
