import { useCallback, useEffect, useMemo, useState } from "react"
import DOMPurify from "dompurify"
import {
  ApiOutlined,
  CodeOutlined,
  DeleteOutlined,
  EditOutlined,
  ExperimentOutlined,
  PlusOutlined,
  ReloadOutlined,
} from "@ant-design/icons"
import {
  Alert,
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Row,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import {
  createProvisionInterface,
  deleteProvisionInterface,
  listProvisionInterfaces,
  listProvisionPlugins,
  testProvisionInterface,
  testProvisionPlugin,
  updateProvisionInterface,
  type ProvisionConfigField,
  type ProvisionInterface,
  type ProvisionManageAction,
  type ProvisionPluginManifest,
  type ProvisionProductPageTab,
  type ProvisionPurchaseField,
  type ProvisionTestLink,
} from "../api/product"

const { Title, Paragraph, Text } = Typography

type TestValues = Record<string, unknown>

function errorMessage(error: unknown, fallback: string) {
  return (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || fallback
}

function statusTag(status?: string) {
  const value = status || "unknown"
  const color: Record<string, string> = {
    stable: "green",
    active: "green",
    beta: "blue",
    draft: "orange",
    disabled: "red",
    deprecated: "red",
  }
  return <Tag color={color[value] || "default"}>{value}</Tag>
}

function actionStyleTag(style?: string) {
  const value = style || "default"
  const color = value === "danger" ? "red" : value === "primary" ? "blue" : "default"
  return <Tag color={color}>{value}</Tag>
}

function boolTag(value?: boolean | null) {
  return value ? <Tag color="green">是</Tag> : <Tag>否</Tag>
}

function formatValue(value: unknown) {
  if (value === undefined || value === null || value === "") return "-"
  if (typeof value === "boolean") return value ? "true" : "false"
  if (typeof value === "object") return JSON.stringify(value)
  return String(value)
}

function listFromRequirement(value: unknown) {
  if (!Array.isArray(value)) return []
  return value.map((item) => String(item)).filter(Boolean)
}

function defaultFieldValues(fields: ProvisionConfigField[] | undefined) {
  const values: TestValues = {}
  for (const field of fields ?? []) {
    if (!field.key) continue
    if (field.default !== undefined) {
      values[field.key] = field.default
    } else if (field.type === "boolean") {
      values[field.key] = false
    }
  }
  return values
}

function numberRuleValue(value: unknown) {
  return typeof value === "number" ? value : undefined
}

function renderConfigInput(field: ProvisionConfigField) {
  const type = (field.type || "text").toLowerCase()
  if (type === "boolean") {
    return <Switch checkedChildren="开" unCheckedChildren="关" />
  }
  if (type === "integer" || type === "number") {
    const validation = field.validation || {}
    return (
      <InputNumber
        min={numberRuleValue(validation.min)}
        max={numberRuleValue(validation.max)}
        precision={type === "integer" ? 0 : undefined}
        style={{ width: "100%" }}
        placeholder={field.placeholder}
      />
    )
  }
  if (type === "select" && field.options?.length) {
    return (
      <Select
        placeholder={field.placeholder}
        options={field.options.map((item) => ({ label: item.label, value: String(item.value) }))}
      />
    )
  }
  if (type === "textarea") {
    return <Input.TextArea rows={3} placeholder={field.placeholder} />
  }
  if (type === "password" || field.secret) {
    return <Input.Password placeholder={field.placeholder} />
  }
  return <Input placeholder={field.placeholder} />
}

function SafeHtml({ html }: { html: string }) {
  return (
    <div
      style={{
        border: "1px solid #f0f0f0",
        borderRadius: 6,
        padding: 16,
        minHeight: 120,
        background: "#fff",
      }}
      dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }}
    />
  )
}

function ChecklistTag({ ok }: { ok: boolean }) {
  return ok ? <Tag color="green">就绪</Tag> : <Tag color="gold">缺失</Tag>
}

function DeveloperChecklist({ plugin, interfaceCount }: { plugin: ProvisionPluginManifest; interfaceCount: number }) {
  const page = plugin.product_page
  const checks = [
    { key: "manifest", label: "Manifest 基础信息", ok: Boolean(plugin.id && plugin.name && plugin.version) },
    { key: "provider", label: "Go 插件入口", ok: Boolean(plugin.provider) },
    { key: "config", label: "接口配置字段", ok: (plugin.config_fields?.length ?? 0) > 0 },
    { key: "purchase", label: "购买参数字段", ok: (page?.purchase_fields?.length ?? 0) > 0 },
    { key: "actions", label: "实例管理动作", ok: (plugin.manage_actions?.length ?? 0) > 0 },
    { key: "tests", label: "测试入口", ok: (plugin.test_links?.length ?? 0) > 0 },
    { key: "interfaces", label: "已保存接口", ok: interfaceCount > 0 },
  ]

  return (
    <Card variant="outlined" title="开发者检查清单">
      <Space orientation="vertical" size={12} style={{ width: "100%" }}>
        <Descriptions column={1} size="small" bordered>
          <Descriptions.Item label="插件 ID"><Text code>{plugin.id}</Text></Descriptions.Item>
          <Descriptions.Item label="源码路径"><Text code>{`mode/provision/${plugin.id}`}</Text></Descriptions.Item>
          <Descriptions.Item label="运行时入口"><Text code>{plugin.provider || `plugin:${plugin.id}`}</Text></Descriptions.Item>
        </Descriptions>
        <Table
          size="small"
          rowKey="key"
          pagination={false}
          dataSource={checks}
          columns={[
            { title: "检查项", dataIndex: "label" },
            { title: "状态", dataIndex: "ok", width: 110, render: (ok: boolean) => <ChecklistTag ok={ok} /> },
          ]}
        />
        <Alert
          type="info"
          showIcon
          title="实现约定"
          description="Go 插件通过 JSON-RPC stdio 实现 provision.product_fields、provision.create 和 provision.manage。完成后创建接口、执行测试、绑定商品，再到插件诊断页回归检查。"
        />
      </Space>
    </Card>
  )
}

export default function AdminProvisionPlugins() {
  const [testForm] = Form.useForm<TestValues>()
  const [interfaceForm] = Form.useForm<Record<string, unknown>>()
  const [plugins, setPlugins] = useState<ProvisionPluginManifest[]>([])
  const [interfaces, setInterfaces] = useState<ProvisionInterface[]>([])
  const [loading, setLoading] = useState(false)
  const [interfaceLoading, setInterfaceLoading] = useState(false)
  const [selectedId, setSelectedId] = useState("")
  const [testingPlugin, setTestingPlugin] = useState<ProvisionPluginManifest | null>(null)
  const [testing, setTesting] = useState(false)
  const [interfaceSaving, setInterfaceSaving] = useState(false)
  const [interfaceTestingId, setInterfaceTestingId] = useState<number | null>(null)
  const [testResult, setTestResult] = useState<Record<string, unknown> | null>(null)
  const [manifestOpen, setManifestOpen] = useState(false)
  const [interfaceModalOpen, setInterfaceModalOpen] = useState(false)
  const [interfacePlugin, setInterfacePlugin] = useState<ProvisionPluginManifest | null>(null)
  const [editingInterface, setEditingInterface] = useState<ProvisionInterface | null>(null)

  const loadPlugins = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listProvisionPlugins()
      setPlugins(res.data ?? [])
    } catch (error) {
      toast.error(errorMessage(error, "加载开通插件失败"))
    } finally {
      setLoading(false)
    }
  }, [])

  const loadInterfaces = useCallback(async () => {
    setInterfaceLoading(true)
    try {
      const res = await listProvisionInterfaces()
      setInterfaces(res.data ?? [])
    } catch (error) {
      toast.error(errorMessage(error, "加载开通接口失败"))
    } finally {
      setInterfaceLoading(false)
    }
  }, [])

  useEffect(() => {
    void loadPlugins()
    void loadInterfaces()
  }, [loadInterfaces, loadPlugins])

  useEffect(() => {
    if (plugins.length === 0) {
      setSelectedId("")
      return
    }
    if (!plugins.some((item) => item.id === selectedId)) {
      setSelectedId(plugins[0].id)
    }
  }, [plugins, selectedId])

  const selectedPlugin = useMemo(
    () => plugins.find((item) => item.id === selectedId) ?? plugins[0] ?? null,
    [plugins, selectedId],
  )

  const selectedPluginInterfaces = useMemo(
    () => interfaces.filter((item) => item.plugin_id === selectedPlugin?.id),
    [interfaces, selectedPlugin],
  )

  const stats = useMemo(() => {
    const manageCount = plugins.reduce((sum, item) => sum + (item.manage_actions?.length ?? 0), 0)
    const testCount = plugins.reduce((sum, item) => sum + (item.test_links?.length ?? 0), 0)
    return { manageCount, testCount }
  }, [plugins])

  const openTest = (plugin: ProvisionPluginManifest) => {
    setTestingPlugin(plugin)
    setTestResult(null)
    testForm.setFieldsValue(defaultFieldValues(plugin.config_fields))
  }

  const openCreateInterface = (plugin: ProvisionPluginManifest) => {
    setInterfacePlugin(plugin)
    setEditingInterface(null)
    setInterfaceModalOpen(true)
    interfaceForm.resetFields()
    interfaceForm.setFieldsValue({
      name: `${plugin.name}接口`,
      enabled: true,
      sort_order: 0,
      remark: "",
      ...defaultFieldValues(plugin.config_fields),
    })
  }

  const openEditInterface = (record: ProvisionInterface) => {
    const plugin = plugins.find((item) => item.id === record.plugin_id) ?? selectedPlugin
    setInterfacePlugin(plugin)
    setEditingInterface(record)
    setInterfaceModalOpen(true)
    interfaceForm.resetFields()
    interfaceForm.setFieldsValue({
      name: record.name,
      enabled: record.enabled,
      sort_order: record.sort_order,
      remark: record.remark ?? "",
      ...(record.config ?? {}),
    })
  }

  const saveInterface = async () => {
    const plugin = interfacePlugin
    if (!plugin) return
    let values: Record<string, unknown>
    try {
      values = await interfaceForm.validateFields()
    } catch {
      return
    }
    const config: Record<string, unknown> = {}
    for (const field of plugin.config_fields ?? []) {
      if (field.key) config[field.key] = values[field.key]
    }
    setInterfaceSaving(true)
    try {
      const payload = {
        name: String(values.name ?? "").trim(),
        plugin_id: plugin.id,
        enabled: Boolean(values.enabled),
        sort_order: Number(values.sort_order ?? 0),
        remark: values.remark ? String(values.remark) : null,
        config,
      }
      if (editingInterface) {
        await updateProvisionInterface(editingInterface.id, payload)
      } else {
        await createProvisionInterface(payload)
      }
      toast.success("开通接口已保存")
      setInterfaceModalOpen(false)
      await loadInterfaces()
    } catch (error) {
      toast.error(errorMessage(error, "保存开通接口失败"))
    } finally {
      setInterfaceSaving(false)
    }
  }

  const runInterfaceTest = async (record: ProvisionInterface) => {
    setInterfaceTestingId(record.id)
    try {
      const res = await testProvisionInterface(record.id)
      const data = res.data ?? {}
      const ok = data.ok !== false
      const message = typeof data.message === "string" ? data.message : ok ? "接口测试通过" : "接口测试失败"
      if (ok) {
        toast.success(message)
      } else {
        toast.error(message)
      }
      await loadInterfaces()
    } catch (error) {
      toast.error(errorMessage(error, "测试开通接口失败"))
    } finally {
      setInterfaceTestingId(null)
    }
  }

  const removeInterface = async (record: ProvisionInterface) => {
    try {
      await deleteProvisionInterface(record.id)
      toast.success("开通接口已删除")
      await loadInterfaces()
    } catch (error) {
      toast.error(errorMessage(error, "删除开通接口失败"))
    }
  }

  const runTest = async () => {
    if (!testingPlugin) return
    let values: TestValues
    try {
      values = await testForm.validateFields()
    } catch {
      return
    }
    setTesting(true)
    try {
      const res = await testProvisionPlugin(testingPlugin.id, values)
      const data = res.data ?? {}
      setTestResult(data)
      const ok = data.ok !== false
      const message = typeof data.message === "string" ? data.message : ok ? "插件测试通过" : "插件测试失败"
      if (ok) {
        toast.success(message)
      } else {
        toast.error(message)
      }
    } catch (error) {
      toast.error(errorMessage(error, "测试开通插件失败"))
    } finally {
      setTesting(false)
    }
  }

  const pluginColumns: TableColumnsType<ProvisionPluginManifest> = [
    {
      title: "插件",
      dataIndex: "name",
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          <Text strong>{record.name}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.id}</Text>
        </Space>
      ),
    },
    { title: "状态", dataIndex: "status", width: 100, render: statusTag },
    {
      title: "能力",
      width: 180,
      render: (_, record) => (
        <Space size={[0, 4]} wrap>
          <Tag color="cyan">provision</Tag>
          {(record.manage_actions?.length ?? 0) > 0 ? <Tag color="blue">管理 {record.manage_actions?.length}</Tag> : null}
          {(record.test_links?.length ?? 0) > 0 ? <Tag color="purple">测试 {record.test_links?.length}</Tag> : null}
        </Space>
      ),
    },
    {
      title: "操作",
      width: 100,
      render: (_, record) => (
        <Button
          size="small"
          icon={<ExperimentOutlined />}
          onClick={(event) => {
            event.stopPropagation()
            openTest(record)
          }}
        >
          测试
        </Button>
      ),
    },
  ]

  const interfaceColumns: TableColumnsType<ProvisionInterface> = [
    {
      title: "接口",
      dataIndex: "name",
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          <Text strong>{record.name}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>#{record.id} / {record.plugin_id}</Text>
        </Space>
      ),
    },
    {
      title: "状态",
      width: 140,
      render: (_value, record) => (
        <Space orientation="vertical" size={2}>
          {record.enabled ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>}
          {record.last_test_ok === null || record.last_test_ok === undefined ? (
            <Tag>未测试</Tag>
          ) : record.last_test_ok ? (
            <Tag color="green">测试通过</Tag>
          ) : (
            <Tag color="red">测试失败</Tag>
          )}
        </Space>
      ),
    },
    {
      title: "配置",
      dataIndex: "config",
      render: (value: ProvisionInterface["config"]) => (
        <Space wrap>
          {Object.keys(value ?? {}).length > 0 ? (
            Object.entries(value ?? {}).map(([key, val]) => (
              <Tag key={key}>{key}: {formatValue(val)}</Tag>
            ))
          ) : (
            <Text type="secondary">未配置</Text>
          )}
        </Space>
      ),
    },
    { title: "最近测试信息", dataIndex: "last_test_message", ellipsis: true, render: (value) => value || "-" },
    {
      title: "操作",
      width: 230,
      align: "right",
      render: (_value, record) => (
        <Space>
          <Button size="small" icon={<ExperimentOutlined />} loading={interfaceTestingId === record.id} onClick={() => void runInterfaceTest(record)}>
            测试
          </Button>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEditInterface(record)}>
            编辑
          </Button>
          <Popconfirm title={`删除接口“${record.name}”？`} okText="删除" cancelText="取消" okButtonProps={{ danger: true }} onConfirm={() => void removeInterface(record)}>
            <Button size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  const configColumns: TableColumnsType<ProvisionConfigField> = [
    { title: "字段", dataIndex: "key", render: (value) => <Text code>{value}</Text> },
    { title: "名称", dataIndex: "label" },
    { title: "类型", dataIndex: "type", render: (value) => <Tag>{value || "text"}</Tag> },
    { title: "必填", dataIndex: "required", render: boolTag },
    { title: "密钥", dataIndex: "secret", render: boolTag },
    { title: "默认值", dataIndex: "default", render: (value) => <Text type="secondary">{formatValue(value)}</Text> },
    { title: "说明", dataIndex: "help", render: (value) => value || "-" },
  ]

  const manageColumns: TableColumnsType<ProvisionManageAction> = [
    { title: "动作", dataIndex: "key", render: (value) => <Text code>{value}</Text> },
    { title: "按钮", dataIndex: "label" },
    { title: "样式", dataIndex: "style", render: actionStyleTag },
    { title: "确认", dataIndex: "confirm", render: boolTag },
    { title: "说明", dataIndex: "description", render: (value) => value || "-" },
  ]

  const testLinkColumns: TableColumnsType<ProvisionTestLink> = [
    { title: "名称", dataIndex: "label" },
    { title: "方法", dataIndex: "method", width: 90, render: (value) => <Tag>{String(value || "POST").toUpperCase()}</Tag> },
    { title: "地址", dataIndex: "url", render: (value) => <Text copyable code>{value}</Text> },
  ]

  const pageTabColumns: TableColumnsType<ProvisionProductPageTab> = [
    { title: "Tab Key", dataIndex: "key", render: (value) => <Text code>{value}</Text> },
    { title: "标题", dataIndex: "label" },
    { title: "HTML 长度", dataIndex: "html", width: 120, render: (value) => `${String(value || "").length} 字符` },
  ]

  const purchaseFieldColumns: TableColumnsType<ProvisionPurchaseField> = [
    { title: "字段", dataIndex: "key", render: (value) => <Text code>{value}</Text> },
    { title: "名称", dataIndex: "label" },
    { title: "类型", dataIndex: "type", render: (value) => <Tag>{value || "text"}</Tag> },
    { title: "必填", dataIndex: "required", render: boolTag },
    { title: "默认值", dataIndex: "default", render: (value) => <Text type="secondary">{formatValue(value)}</Text> },
    { title: "说明", dataIndex: "help", render: (value) => value || "-" },
  ]

  const renderRequirements = (plugin: ProvisionPluginManifest) => {
    const requirements = plugin.requirements || {}
    const pythonPackages = listFromRequirement(requirements.python_packages)
    const network = listFromRequirement(requirements.network)
    return (
      <Descriptions column={1} size="small" bordered>
        <Descriptions.Item label="Python 包">
          {pythonPackages.length > 0 ? pythonPackages.map((item) => <Tag key={item}>{item}</Tag>) : "-"}
        </Descriptions.Item>
        <Descriptions.Item label="网络依赖">
          {network.length > 0 ? network.map((item) => <Tag key={item}>{item}</Tag>) : "-"}
        </Descriptions.Item>
      </Descriptions>
    )
  }

  const renderProductPage = (plugin: ProvisionPluginManifest) => {
    const page = plugin.product_page
    const tabs = page?.tabs ?? []
    return (
      <Space orientation="vertical" size={16} style={{ width: "100%" }}>
        <Descriptions column={1} size="small" bordered>
          <Descriptions.Item label="布局">{page?.layout || "-"}</Descriptions.Item>
          <Descriptions.Item label="购买字段">{page?.purchase_fields?.length ?? 0}</Descriptions.Item>
          <Descriptions.Item label="标签页">{tabs.length}</Descriptions.Item>
        </Descriptions>
        {page?.summary_html ? <SafeHtml html={page.summary_html} /> : null}
        <Table
          size="small"
          rowKey="key"
          pagination={false}
          dataSource={tabs}
          columns={pageTabColumns}
          locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无页面标签" /> }}
        />
      </Space>
    )
  }

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>开通插件工作台</Title>
          <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
            查看插件 manifest、配置开通接口、执行测试，并在绑定商品前完成开发者检查。
          </Paragraph>
        </Col>
        <Col>
          <Space>
            <Button icon={<ReloadOutlined />} loading={loading || interfaceLoading} onClick={() => { void loadPlugins(); void loadInterfaces() }}>
              刷新
            </Button>
            {selectedPlugin ? (
              <Button type="primary" icon={<PlusOutlined />} onClick={() => openCreateInterface(selectedPlugin)}>
                新建接口
              </Button>
            ) : null}
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="插件" value={plugins.length} prefix={<ApiOutlined />} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="接口" value={interfaces.length} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="管理动作" value={stats.manageCount} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="测试入口" value={stats.testCount} /></Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} align="stretch">
        <Col xs={24} xl={9}>
          <Card variant="outlined" title="插件 Manifest">
            <Table
              size="small"
              rowKey="id"
              loading={loading}
              pagination={false}
              dataSource={plugins}
              columns={pluginColumns}
              onRow={(record) => ({
                onClick: () => setSelectedId(record.id),
                style: {
                  cursor: "pointer",
                  background: record.id === selectedPlugin?.id ? "#f0f7ff" : undefined,
                },
              })}
              locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无开通插件" /> }}
            />
          </Card>
        </Col>
        <Col xs={24} xl={15}>
          {selectedPlugin ? (
            <Space orientation="vertical" size={16} style={{ width: "100%" }}>
              <Card
                variant="outlined"
                title={selectedPlugin.name}
                extra={(
                  <Space>
                    {statusTag(selectedPlugin.status)}
                    <Button size="small" icon={<ExperimentOutlined />} onClick={() => openTest(selectedPlugin)}>测试</Button>
                    <Button size="small" icon={<CodeOutlined />} onClick={() => setManifestOpen(true)}>Manifest</Button>
                  </Space>
                )}
              >
                <Descriptions column={2} size="small" bordered>
                  <Descriptions.Item label="插件 ID"><Text code>{selectedPlugin.id}</Text></Descriptions.Item>
                  <Descriptions.Item label="版本">{selectedPlugin.version || "-"}</Descriptions.Item>
                  <Descriptions.Item label="Provider">{selectedPlugin.provider || "-"}</Descriptions.Item>
                  <Descriptions.Item label="作者">{selectedPlugin.author?.name || "-"}</Descriptions.Item>
                  <Descriptions.Item label="说明" span={2}>{selectedPlugin.description || "-"}</Descriptions.Item>
                </Descriptions>
              </Card>

              <DeveloperChecklist plugin={selectedPlugin} interfaceCount={selectedPluginInterfaces.length} />
            </Space>
          ) : (
            <Card variant="outlined"><Empty description="请选择插件" /></Card>
          )}
        </Col>
      </Row>

      {selectedPlugin ? (
        <Tabs
          items={[
            {
              key: "interfaces",
              label: "接口",
              children: (
                <Card
                  variant="outlined"
                  title="已保存接口"
                  extra={<Button size="small" type="primary" icon={<PlusOutlined />} onClick={() => openCreateInterface(selectedPlugin)}>新建接口</Button>}
                >
                  <Table
                    rowKey="id"
                    loading={interfaceLoading}
                    dataSource={selectedPluginInterfaces}
                    columns={interfaceColumns}
                    pagination={false}
                    scroll={{ x: 900 }}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="该插件暂无接口" /> }}
                  />
                </Card>
              ),
            },
            {
              key: "config",
              label: "配置字段",
              children: (
                <Card variant="outlined" title="接口配置字段">
                  <Table
                    size="small"
                    rowKey="key"
                    pagination={false}
                    dataSource={selectedPlugin.config_fields ?? []}
                    columns={configColumns}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无配置字段" /> }}
                  />
                </Card>
              ),
            },
            {
              key: "purchase",
              label: "购买字段",
              children: (
                <Card variant="outlined" title="商品购买字段">
                  <Table
                    size="small"
                    rowKey="key"
                    pagination={false}
                    dataSource={selectedPlugin.product_page?.purchase_fields ?? []}
                    columns={purchaseFieldColumns}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无购买字段" /> }}
                  />
                </Card>
              ),
            },
            {
              key: "manage",
              label: "管理动作",
              children: (
                <Card variant="outlined" title="实例管理动作">
                  <Table
                    size="small"
                    rowKey="key"
                    pagination={false}
                    dataSource={selectedPlugin.manage_actions ?? []}
                    columns={manageColumns}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无管理动作" /> }}
                  />
                </Card>
              ),
            },
            {
              key: "tests",
              label: "测试入口",
              children: (
                <Card variant="outlined" title="测试入口">
                  <Table
                    size="small"
                    rowKey={(record) => `${record.method || "POST"}-${record.url}`}
                    pagination={false}
                    dataSource={selectedPlugin.test_links ?? []}
                    columns={testLinkColumns}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无测试入口" /> }}
                  />
                </Card>
              ),
            },
            {
              key: "page",
              label: "商品页",
              children: <Card variant="outlined" title="商品页预览">{renderProductPage(selectedPlugin)}</Card>,
            },
            {
              key: "requirements",
              label: "运行依赖",
              children: <Card variant="outlined" title="运行依赖">{renderRequirements(selectedPlugin)}</Card>,
            },
          ]}
        />
      ) : null}

      <Modal
        title={testingPlugin ? `测试 ${testingPlugin.name}` : "测试插件"}
        open={!!testingPlugin}
        onCancel={() => setTestingPlugin(null)}
        onOk={() => void runTest()}
        confirmLoading={testing}
        width={760}
      >
        {testingPlugin ? (
          <Space orientation="vertical" size={16} style={{ width: "100%" }}>
            <Alert type="info" showIcon title="这里会使用下方配置调用插件测试钩子。" />
            <Form form={testForm} layout="vertical">
              {(testingPlugin.config_fields ?? []).map((field) => (
                <Form.Item
                  key={field.key}
                  name={field.key}
                  label={field.label || field.key}
                  valuePropName={(field.type || "").toLowerCase() === "boolean" ? "checked" : "value"}
                  rules={field.required ? [{ required: true, message: `请填写${field.label || field.key}` }] : undefined}
                  extra={field.help}
                >
                  {renderConfigInput(field)}
                </Form.Item>
              ))}
            </Form>
            {testResult ? (
              <pre style={{ margin: 0, padding: 12, background: "#f6f8fa", borderRadius: 6, maxHeight: 260, overflow: "auto" }}>
                {JSON.stringify(testResult, null, 2)}
              </pre>
            ) : null}
          </Space>
        ) : null}
      </Modal>

      <Modal
        title={editingInterface ? "编辑开通接口" : "创建开通接口"}
        open={interfaceModalOpen}
        onCancel={() => setInterfaceModalOpen(false)}
        onOk={() => void saveInterface()}
        confirmLoading={interfaceSaving}
        width={760}
      >
        {interfacePlugin ? (
          <Form form={interfaceForm} layout="vertical">
            <Row gutter={12}>
              <Col xs={24} md={16}>
                <Form.Item name="name" label="名称" rules={[{ required: true, message: "请填写名称" }]}>
                  <Input />
                </Form.Item>
              </Col>
              <Col xs={12} md={4}>
                <Form.Item name="enabled" label="启用" valuePropName="checked">
                  <Switch checkedChildren="开" unCheckedChildren="关" />
                </Form.Item>
              </Col>
              <Col xs={12} md={4}>
                <Form.Item name="sort_order" label="排序">
                  <InputNumber precision={0} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item name="remark" label="备注">
              <Input.TextArea rows={2} />
            </Form.Item>
            {(interfacePlugin.config_fields ?? []).map((field) => (
              <Form.Item
                key={field.key}
                name={field.key}
                label={field.label || field.key}
                valuePropName={(field.type || "").toLowerCase() === "boolean" ? "checked" : "value"}
                rules={field.required ? [{ required: true, message: `请填写${field.label || field.key}` }] : undefined}
                extra={field.help}
              >
                {renderConfigInput(field)}
              </Form.Item>
            ))}
          </Form>
        ) : null}
      </Modal>

      <Modal
        title="Manifest JSON"
        open={manifestOpen}
        onCancel={() => setManifestOpen(false)}
        footer={<Button onClick={() => setManifestOpen(false)}>关闭</Button>}
        width={860}
      >
        <pre style={{ margin: 0, padding: 12, background: "#f6f8fa", borderRadius: 6, maxHeight: 560, overflow: "auto" }}>
          {JSON.stringify(selectedPlugin, null, 2)}
        </pre>
      </Modal>
    </Space>
  )
}
