"use client";

import { Table, Empty, Tag, Typography } from "antd";
import { useMemo } from "react";
import type { ParsedProject } from "@/services/project";

interface ArtifactRow {
  key: string;
  mc_version: string;
  artifact: string | null;
  sources: string | null;
}

interface VersionTableProps {
  project: ParsedProject | null;
  loading: boolean;
  onLoadingChange: (loading: boolean) => void;
}

export function VersionTable({
  project,
  loading,
  onLoadingChange,
}: VersionTableProps) {
  const dataSource: ArtifactRow[] = useMemo(() => {
    if (!project) return [];
    return project.artifacts.map((a) => ({
      key: a.mc_version,
      mc_version: a.mc_version,
      artifact: a.artifact,
      sources: a.sources,
    }));
  }, [project]);

  const columns = [
    {
      title: "MC 版本",
      dataIndex: "mc_version",
      key: "mc_version",
      width: 120,
      render: (val: string) => <Tag>{val}</Tag>,
    },
    {
      title: "兼容范围",
      dataIndex: "mc_version",
      key: "range",
      width: 200,
      render: (_: string, __: ArtifactRow, index: number) => {
        const isLast =
          project && index === project.artifacts.length - 1;
        // 兼容范围在发布前由 PublishModal 加载元数据后完整计算
        // 此处仅作占位显示
        return isLast ? (
          <Tag color="blue">加载元数据后计算</Tag>
        ) : (
          <Typography.Text type="secondary">—</Typography.Text>
        );
      },
    },
    {
      title: "构建产物",
      dataIndex: "artifact",
      key: "artifact",
      ellipsis: true,
      render: (val: string | null) =>
        val ? (
          <Typography.Text>{val}</Typography.Text>
        ) : (
          <Typography.Text type="danger">文件不存在</Typography.Text>
        ),
    },
    {
      title: "源码",
      dataIndex: "sources",
      key: "sources",
      ellipsis: true,
      render: (val: string | null) =>
        val ? (
          <Typography.Text>{val}</Typography.Text>
        ) : (
          <Typography.Text type="danger">文件不存在</Typography.Text>
        ),
    },
  ];

  if (!project) {
    return (
      <Empty
        description="请选择一个配置以查看版本信息"
        style={{ padding: 40 }}
      />
    );
  }

  return (
    <Table<ArtifactRow>
      dataSource={dataSource}
      columns={columns}
      loading={loading}
      pagination={false}
      size="middle"
      bordered
      locale={{
        emptyText: "未找到构建产物",
      }}
    />
  );
}
