import { useEffect, useState } from "react";
import { App as AntApp, Button, Card, Space, Table, Tag, Typography, message } from "antd";
import { ReloadOutlined, ImportOutlined } from "@ant-design/icons";
import { Session, ensureAppsImport, listApps } from "./api";

type Mod = {
  app_id: string;
  slug: string;
  name: string;
  status: string;
  status_label?: string;
  building?: boolean;
  page_count: number;
  entity_count: number;
  updated_at: string;
};

export function ModulesPage(props: {
  session: Session;
  onOpenPublished: (slug: string) => void;
  onContinueDraft: (slug: string) => void;
}) {
  const { session, onOpenPublished, onContinueDraft } = props;
  const { modal } = AntApp.useApp();
  const [items, setItems] = useState<Mod[]>([]);
  const [scope, setScope] = useState("");
  const [loading, setLoading] = useState(false);
  const [ensuring, setEnsuring] = useState(false);

  async function refresh() {
    setLoading(true);
    try {
      const res = await listApps(session);
      setItems(res.items || []);
      setScope((res as any).scope || "");
    } catch (e: any) {
      message.error(e.message || String(e));
    } finally {
      setLoading(false);
    }
  }

  function onEnsureImport() {
    modal.confirm({
      title: "一键开启全部业务表导入？",
      content: "将为本公司所有已发布模块补齐蓝图 import/export（无需逐个再发布）。只读表不会改动。",
      okText: "开启",
      onOk: async () => {
        setEnsuring(true);
        try {
          const res = await ensureAppsImport(session, false);
          message.success(res.message || `已更新 ${res.updated} 个模块`);
          await refresh();
        } catch (e: any) {
          message.error(e.message || String(e));
          throw e;
        } finally {
          setEnsuring(false);
        }
      },
    });
  }

  useEffect(() => {
    refresh();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [session.accessToken]);

  const statusTag = (r: Mod) => {
    const label = r.status_label || r.status;
    if (r.status === "published") return <Tag color="success">{label}</Tag>;
    if (r.status === "failed") return <Tag color="error">{label}</Tag>;
    return <Tag color="processing">{label || "在建"}</Tag>;
  };

  return (
    <Card
      title="模块管理"
      extra={
        <Space>
          <Button icon={<ImportOutlined />} loading={ensuring} onClick={() => onEnsureImport()}>
            一键开启导入
          </Button>
          <Button icon={<ReloadOutlined />} onClick={refresh} loading={loading}>
            刷新
          </Button>
        </Space>
      }
    >
      <Typography.Paragraph type="secondary" style={{ marginTop: 0 }}>
        管理账号（如 owner）可查看本租户<strong>全部模块</strong>，含<strong>在建</strong>与已发布。
        智能体默认不限制模块（可自由发布自建 slug）；仅当配置了白名单时才受限。
        「一键开启导入」修复旧模块因蓝图缺 import 导致的导入 400（Z9e）。
        {scope === "all"
          ? " 当前范围：管理全部。"
          : scope === "open"
            ? " 当前范围：智能体开放。"
            : scope === "granted"
              ? " 当前范围：白名单。"
              : null}
      </Typography.Paragraph>
      <Table
        rowKey="app_id"
        loading={loading}
        dataSource={items}
        pagination={{ pageSize: 20 }}
        columns={[
          { title: "模块名称", dataIndex: "name" },
          { title: "slug", dataIndex: "slug", render: (v) => <Typography.Text code>{v}</Typography.Text> },
          { title: "状态", width: 110, render: (_, r) => statusTag(r) },
          { title: "页面数", dataIndex: "page_count", width: 80 },
          { title: "实体数", dataIndex: "entity_count", width: 80 },
          { title: "更新时间", dataIndex: "updated_at", width: 200 },
          {
            title: "操作",
            width: 200,
            render: (_, r) => (
              <Space>
                {r.status === "published" ? (
                  <Button type="link" onClick={() => onOpenPublished(r.slug)}>
                    打开
                  </Button>
                ) : (
                  <Button type="link" onClick={() => onContinueDraft(r.slug)}>
                    继续编辑
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        locale={{ emptyText: "暂无模块。生成蓝图后会登记为「在建」，发布成功后变为「已发布」。" }}
      />
    </Card>
  );
}
