"use client";

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

interface Repo {
  id: string;
  repoName: string;
  projectId: string;
  projectName: string;
  workspaceName: string;
  defaultBranch: string;
  isPrivate: boolean;
  createdBy: string;
  createdAt: string;
  aiCodeReviewEnabled: boolean;
  collaboratorCount: number;
  branchCount: number;
}

export default function ReposPage() {
  const [repos, setRepos] = useState<Repo[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const pageSize = 30;

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

  function loadRepos() {
    setLoading(true);
    const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize) });
    if (search) params.set("search", search);
    fetch(`/api/platform/repos?${params}`)
      .then((r) => r.json())
      .then((data) => {
        setRepos(data.repos || []);
        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">Git 仓库（只读）</p>
      </div>

      <div className="toolbar">
        <input
          type="text"
          className="form-input search-input"
          placeholder="搜索仓库名称..."
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(1); }}
        />
      </div>

      <div className="card">
        {loading ? <div className="loading">加载中...</div> : repos.length === 0 ? (
          <div className="empty-state">
            <div className="empty-state-icon">📦</div>
            <p>暂无仓库</p>
          </div>
        ) : (
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>仓库名称</th>
                  <th>所属项目</th>
                  <th>可见性</th>
                  <th>默认分支</th>
                  <th>协作者</th>
                  <th>分支</th>
                  <th>AI Review</th>
                  <th>创建时间</th>
                </tr>
              </thead>
              <tbody>
                {repos.map((repo) => (
                  <tr key={repo.id}>
                    <td>
                      <Link href={`/admin/repos/${repo.id}`}>
                        <code style={{ fontSize: "12px", cursor: "pointer", color: "#2563eb" }}>{repo.repoName}</code>
                      </Link>
                    </td>
                    <td>
                      <span style={{ fontSize: "12px" }}>
                        {repo.workspaceName ? `${repo.workspaceName} / ` : ""}
                        {repo.projectName}
                      </span>
                    </td>
                    <td>
                      <span className={`badge ${repo.isPrivate ? "badge-neutral" : "badge-success"}`}>
                        {repo.isPrivate ? "私有" : "公开"}
                      </span>
                    </td>
                    <td style={{ fontSize: "12px", fontFamily: "monospace" }}>
                      {repo.defaultBranch || "main"}
                    </td>
                    <td>{repo.collaboratorCount}</td>
                    <td>{repo.branchCount}</td>
                    <td>
                      <span className={`badge ${repo.aiCodeReviewEnabled ? "badge-success" : "badge-neutral"}`}>
                        {repo.aiCodeReviewEnabled ? "启用" : "禁用"}
                      </span>
                    </td>
                    <td style={{ fontSize: "12px" }}>
                      {format(parseISO(repo.createdAt), "yyyy-MM-dd")}
                    </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>
  );
}
