"use client";

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

interface Branch {
  name: string;
  oid: string;
  isHead: boolean;
  upstream: string | null;
  createdAt: string;
}

interface Commit {
  id: number;
  oid: string;
  shortOid: string;
  authorName: string;
  authorEmail: string;
  message: string;
  shortMessage: string;
  createdAt: string;
}

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

type Tab = "branches" | "commits";

export default function RepoDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [repo, setRepo] = useState<Repo | null>(null);
  const [branches, setBranches] = useState<Branch[]>([]);
  const [commits, setCommits] = useState<Commit[]>([]);
  const [tab, setTab] = useState<Tab>("branches");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!id) return;
    fetch(`/api/admin/repos/${id}`)
      .then((r) => r.json())
      .then((data) => {
        if (data.error) { setError(data.error); return; }
        setRepo(data.repo);
        setBranches(data.branches || []);
        setCommits(data.commits || []);
      })
      .catch((e) => setError(String(e)))
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) return <div className="admin-content"><div className="loading">加载中...</div></div>;
  if (error) return <div className="admin-content"><div className="alert alert-error">{error}</div></div>;
  if (!repo) return null;

  return (
    <div className="admin-content">
      <div className="page-header">
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "4px" }}>
            <Link href="/admin/repos" style={{ color: "#737373", fontSize: "13px" }}>← 仓库列表</Link>
          </div>
          <h1 className="page-title">
            <code>{repo.repoName}</code>
          </h1>
          <p className="page-subtitle">
            {repo.workspaceName ? `${repo.workspaceName} / ` : ""}{repo.projectName}
            {" · "}
            <span className={`badge ${repo.isPrivate ? "badge-neutral" : "badge-success"}`}>
              {repo.isPrivate ? "私有" : "公开"}
            </span>
            {" · "}
            默认分支: <code>{repo.defaultBranch}</code>
          </p>
        </div>
        <span className={`badge ${repo.aiCodeReviewEnabled ? "badge-success" : "badge-neutral"}`}>
          AI Review {repo.aiCodeReviewEnabled ? "启用" : "禁用"}
        </span>
      </div>

      {/* Repo info card */}
      <div className="card" style={{ marginBottom: "16px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: "16px" }}>
          <div>
            <div style={{ fontSize: "12px", color: "#737373", marginBottom: "4px" }}>描述</div>
            <div style={{ fontSize: "14px" }}>{repo.description || "无描述"}</div>
          </div>
          <div>
            <div style={{ fontSize: "12px", color: "#737373", marginBottom: "4px" }}>创建者</div>
            <div style={{ fontSize: "14px" }}><code>{repo.createdBy}</code></div>
          </div>
          <div>
            <div style={{ fontSize: "12px", color: "#737373", marginBottom: "4px" }}>创建时间</div>
            <div style={{ fontSize: "14px" }}>{format(parseISO(repo.createdAt), "yyyy-MM-dd HH:mm")}</div>
          </div>
          <div>
            <div style={{ fontSize: "12px", color: "#737373", marginBottom: "4px" }}>协作者</div>
            <div style={{ fontSize: "14px" }}>{repo.collaboratorCount} 人</div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="toolbar">
        <button className={`btn btn-sm ${tab === "branches" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("branches")}>
          分支 ({branches.length})
        </button>
        <button className={`btn btn-sm ${tab === "commits" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("commits")}>
          最近提交 ({commits.length})
        </button>
      </div>

      <div className="card">
        {tab === "branches" && (
          branches.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>Commit OID</th><th>HEAD</th><th>Upstream</th><th>更新时间</th></tr></thead>
                <tbody>
                  {branches.map((b) => (
                    <tr key={b.name}>
                      <td><code style={{ fontSize: "12px" }}>{b.name}</code></td>
                      <td><code style={{ fontSize: "11px", color: "#737373" }}>{b.oid.slice(0, 8)}</code></td>
                      <td>{b.isHead ? <span className="badge badge-success">HEAD</span> : null}</td>
                      <td style={{ fontSize: "12px", color: "#737373" }}>{b.upstream || "-"}</td>
                      <td style={{ fontSize: "12px" }}>{format(parseISO(b.createdAt), "yyyy-MM-dd HH:mm")}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )
        )}

        {tab === "commits" && (
          commits.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>OID</th><th>提交信息</th><th>作者</th><th>时间</th></tr></thead>
                <tbody>
                  {commits.map((c) => (
                    <tr key={c.id}>
                      <td><code style={{ fontSize: "11px", color: "#737373" }}>{c.shortOid}</code></td>
                      <td style={{ fontSize: "13px", maxWidth: "400px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={c.message}>{c.shortMessage}</td>
                      <td style={{ fontSize: "12px" }}>{c.authorName} &lt;{c.authorEmail}&gt;</td>
                      <td style={{ fontSize: "12px" }}>{format(parseISO(c.createdAt), "yyyy-MM-dd HH:mm")}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )
        )}
      </div>
    </div>
  );
}
