import { useCallback, useEffect, useMemo, useState } from "react"
import type { ReactNode } from "react"
import { Link } from "react-router-dom"
import {
  ApiOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExperimentOutlined,
  FileSearchOutlined,
  ReloadOutlined,
  SafetyCertificateOutlined,
  SettingOutlined,
  SyncOutlined,
  WarningOutlined,
} from "@ant-design/icons"
import {
  Alert,
  Button,
  Card,
  Col,
  Empty,
  Modal,
  Row,
  Skeleton,
  Space,
  Statistic,
  Table,
  Tabs,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import { provisionAdminInstance } from "../api/instances"
import {
  getPluginDiagnostics,
  type NotificationChannelDiagnostic,
  type PluginDiagnosticWarning,
  type PluginDiagnostics,
  type ProductBindingIssue,
  type ProvisionInterfaceDiagnostic,
  type ProvisionPluginDiagnostic,
  type RecentProvisionFailure,
  type SecretDiagnosticItem,
  type VerificationRecordDiagnostic,
} from "../api/pluginDiagnostics"
import { testProvisionInterface } from "../api/product"
import { runTask } from "../api/tasks"
import { syncAdminUpstreamActions } from "../api/upstream_actions"

const { Title, Paragraph, Text } = Typography

const STATUS_META: Record<string, { label: string; color: string; icon?: ReactNode }> = {
  ok: { label: "正常", color: "green", icon: <CheckCircleOutlined /> },
  warning: { label: "需关注", color: "gold", icon: <WarningOutlined /> },
  error: { label: "异常", color: "red", icon: <CloseCircleOutlined /> },
  disabled: { label: "已禁用", color: "default" },
  encrypted: { label: "已加密", color: "green" },
  plaintext: { label: "明文", color: "red" },
  empty: { label: "未填写", color: "default" },
}

const INSTANCE_STATUS_META: Record<string, { label: string; color: string }> = {
  provisioning: { label: "开通中", color: "blue" },
  active: { label: "运行中", color: "green" },
  suspended: { label: "已暂停", color: "gold" },
  terminated: { label: "已销毁", color: "default" },
  failed: { label: "失败", color: "red" },
  provision_failed: { label: "开通失败", color: "red" },
}

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

function statusTag(value?: string | null) {
  const key = value || "unknown"
  const meta = STATUS_META[key] ?? INSTANCE_STATUS_META[key] ?? { label: key, color: "default" }
  return (
    <Tag color={meta.color} icon={"icon" in meta ? meta.icon : undefined}>
      {meta.label}
    </Tag>
  )
}

function levelTag(level: string) {
  return level === "error" ? <Tag color="red">错误</Tag> : <Tag color="gold">提醒</Tag>
}

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

function formatDate(value?: string | null) {
  if (!value) return "-"
  return new Date(value).toLocaleString("zh-CN", {
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  })
}

function textOrDash(value?: string | number | null) {
  if (value === undefined || value === null || value === "") return <Text type="secondary">-</Text>
  return String(value)
}

function renderTags(values: string[]) {
  if (!values.length) return <Text type="secondary">-</Text>
  return (
    <Space size={[4, 4]} wrap>
      {values.map((item) => (
        <Tag key={item}>{item}</Tag>
      ))}
    </Space>
  )
}

function renderAction(path?: string, label = "查看") {
  if (!path) return <Text type="secondary">-</Text>
  return (
    <Link to={path}>
      <Button size="small" icon={<FileSearchOutlined />}>
        {label}
      </Button>
    </Link>
  )
}

export default function AdminPluginDiagnostics() {
  const [loading, setLoading] = useState(true)
  const [diagnostics, setDiagnostics] = useState<PluginDiagnostics | null>(null)
  const [actionLoading, setActionLoading] = useState<string | null>(null)

  const loadDiagnostics = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getPluginDiagnostics()
      setDiagnostics(res.data ?? null)
    } catch (error) {
      toast.error(errorMessage(error, "加载插件诊断失败"))
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void loadDiagnostics()
  }, [loadDiagnostics])

  const runDiagnosticAction = async (key: string, label: string, fn: () => Promise<unknown>) => {
    setActionLoading(key)
    try {
      await fn()
      toast.success(`${label}已完成`)
      await loadDiagnostics()
    } catch (error) {
      toast.error(errorMessage(error, `${label}失败`))
    } finally {
      setActionLoading(null)
    }
  }

  const confirmProvisionRetry = (record: RecentProvisionFailure) => {
    Modal.confirm({
      title: "重新触发开通",
      content: `确认重新开通实例 #${record.instance_id}？系统会复用订单快照重新调用开通链路。`,
      okText: "重新开通",
      cancelText: "取消",
      onOk: () => runDiagnosticAction(
        `provision-${record.instance_id}`,
        "重新开通",
        () => provisionAdminInstance(record.instance_id),
      ),
    })
  }

  const summary = diagnostics?.summary
  const alertType = summary?.error_count ? "error" : summary?.warning_count ? "warning" : "success"
  const alertMessage = summary?.issue_count
    ? `发现 ${summary.error_count} 个错误、${summary.warning_count} 个提醒`
    : "当前未发现阻断插件链路的问题"

  const statItems = useMemo(() => [
    {
      title: "待处理问题",
      value: summary?.issue_count ?? 0,
      color: (summary?.error_count ?? 0) > 0 ? "#ff4d4f" : "#faad14",
      icon: <WarningOutlined />,
    },
    {
      title: "启用插件",
      value: summary?.enabled_plugins ?? 0,
      color: "#1677ff",
      icon: <ApiOutlined />,
    },
    {
      title: "失败实例",
      value: summary?.recent_failed_instances ?? 0,
      color: "#ff4d4f",
      icon: <SyncOutlined />,
    },
    {
      title: "待处理实名",
      value: summary?.pending_redirect_verifications ?? 0,
      color: "#722ed1",
      icon: <SafetyCertificateOutlined />,
    },
    {
      title: "明文密钥",
      value: summary?.plaintext_secret_count ?? 0,
      color: "#cf1322",
      icon: <SettingOutlined />,
    },
  ], [summary])

  const warningColumns: TableColumnsType<PluginDiagnosticWarning> = [
    { title: "级别", dataIndex: "level", width: 90, render: levelTag },
    { title: "范围", dataIndex: "scope", width: 150 },
    { title: "问题", dataIndex: "message", width: 240 },
    { title: "建议", dataIndex: "suggestion", render: textOrDash },
    { title: "操作", dataIndex: "path", width: 120, render: (path) => renderAction(path) },
  ]

  const channelColumns: TableColumnsType<NotificationChannelDiagnostic> = [
    { title: "通道", dataIndex: "label", width: 120 },
    { title: "状态", dataIndex: "status", width: 110, render: statusTag },
    {
      title: "插件",
      width: 120,
      render: (_, record) => `${record.enabled_count}/${record.total_plugins}`,
    },
    {
      title: "当前插件",
      render: (_, record) => renderTags(record.current_plugins.map((item) => item.name || item.id).filter(Boolean)),
    },
    {
      title: "缺少配置",
      render: (_, record) => renderTags(record.missing_required.map((item) => `${item.plugin_name || item.plugin_id || ""}${item.plugin_name || item.plugin_id ? " / " : ""}${item.label}`)),
    },
    { title: "告警", render: (_, record) => renderTags(record.warnings) },
    {
      title: "操作",
      width: 130,
      render: (_, record) => renderAction(record.actions[0]?.path, record.actions[0]?.label || "配置"),
    },
  ]

  const provisionPluginColumns: TableColumnsType<ProvisionPluginDiagnostic> = [
    {
      title: "插件",
      dataIndex: "name",
      render: (value, record) => (
        <Space>
          <Text strong>{value}</Text>
          <Tag>{record.id}</Tag>
        </Space>
      ),
    },
    { title: "版本", dataIndex: "version", width: 100, render: textOrDash },
    { title: "接口", width: 120, render: (_, record) => `${record.enabled_interface_count}/${record.interface_count}` },
    { title: "商品", width: 120, render: (_, record) => `${record.active_product_count}/${record.product_count}` },
    { title: "配置字段", dataIndex: "config_field_count", width: 120 },
    { title: "购买字段", dataIndex: "purchase_field_count", width: 130 },
    { title: "管理动作", dataIndex: "manage_action_count", width: 130 },
  ]

  const interfaceColumns: TableColumnsType<ProvisionInterfaceDiagnostic> = [
    {
      title: "接口",
      dataIndex: "name",
      render: (value, record) => (
        <Space>
          <Text strong>{value}</Text>
          <Tag>{record.plugin_name}</Tag>
        </Space>
      ),
    },
    { title: "状态", dataIndex: "status", width: 100, render: statusTag },
    { title: "启用", dataIndex: "enabled", width: 90, render: boolTag },
    {
      title: "最近测试",
      dataIndex: "last_test_ok",
      width: 120,
      render: (value) => value === true ? <Tag color="green">通过</Tag> : value === false ? <Tag color="red">失败</Tag> : <Tag>未测试</Tag>,
    },
    {
      title: "问题",
      render: (_, record) => renderTags([
        ...record.warnings,
        ...record.missing_required.map((item) => `缺少 ${item.label}`),
      ]),
    },
    { title: "更新时间", dataIndex: "updated_at", width: 140, render: formatDate },
    {
      title: "操作",
      width: 110,
      render: (_, record) => (
        <Button
          size="small"
          icon={<ExperimentOutlined />}
          disabled={!record.enabled}
          loading={actionLoading === `test-interface-${record.id}`}
          onClick={() => runDiagnosticAction(
            `test-interface-${record.id}`,
            "测试开通接口",
            () => testProvisionInterface(record.id),
          )}
        >
          测试
        </Button>
      ),
    },
  ]

  const productIssueColumns: TableColumnsType<ProductBindingIssue> = [
    {
      title: "商品",
      dataIndex: "product_name",
      render: (value, record) => (
        <Space orientation="vertical" size={0}>
          <Link to={`/admin/products/${record.product_id}`}>{value}</Link>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.sku}</Text>
        </Space>
      ),
    },
    { title: "状态", dataIndex: "status", width: 100, render: statusTag },
    { title: "自动开通", dataIndex: "auto_provision", width: 120, render: boolTag },
    { title: "插件", dataIndex: "plugin_id", width: 150, render: textOrDash },
    { title: "接口 ID", dataIndex: "interface_id", width: 110, render: textOrDash },
    { title: "问题", dataIndex: "issues", render: renderTags },
  ]

  const failureColumns: TableColumnsType<RecentProvisionFailure> = [
    {
      title: "实例",
      dataIndex: "instance_id",
      width: 110,
      render: (value) => <Link to={`/admin/instances/${value}`}>#{value}</Link>,
    },
    {
      title: "商品",
      dataIndex: "product_name",
      render: (value, record) => (
        <Space>
          <Text>{value}</Text>
          <Tag>{record.plugin_id || "-"}</Tag>
        </Space>
      ),
    },
    { title: "用户", dataIndex: "username", width: 130 },
    { title: "订单", dataIndex: "out_order_no", width: 180 },
    { title: "状态", dataIndex: "status", width: 130, render: statusTag },
    { title: "尝试次数", dataIndex: "attempts", width: 90 },
    { title: "更新时间", dataIndex: "updated_at", width: 140, render: formatDate },
    { title: "日志", dataIndex: "provision_log", ellipsis: true, render: textOrDash },
    {
      title: "操作",
      width: 130,
      render: (_, record) => (
        <Button
          size="small"
          danger
          loading={actionLoading === `provision-${record.instance_id}`}
          onClick={() => confirmProvisionRetry(record)}
        >
          重试
        </Button>
      ),
    },
  ]

  const verificationColumns: TableColumnsType<VerificationRecordDiagnostic> = [
    { title: "记录", dataIndex: "id", width: 90 },
    { title: "用户", dataIndex: "username", width: 140 },
    { title: "服务商", dataIndex: "provider", ellipsis: true },
    { title: "方式", dataIndex: "mode", width: 130 },
    { title: "状态", dataIndex: "status", width: 110, render: statusTag },
    { title: "外部 ID", dataIndex: "external_id", width: 180, render: textOrDash },
    { title: "更新时间", dataIndex: "updated_at", width: 140, render: formatDate },
  ]

  const secretColumns: TableColumnsType<SecretDiagnosticItem> = [
    { title: "范围", dataIndex: "scope", width: 160, render: (value) => value === "system_setting" ? "系统配置" : "开通接口" },
    {
      title: "名称",
      dataIndex: "label",
      render: (value, record) => (
        <Space>
          <Text>{value}</Text>
          <Tag>{record.key}</Tag>
        </Space>
      ),
    },
    { title: "插件 / 接口", render: (_, record) => record.interface_name || record.plugin || <Text type="secondary">-</Text> },
    { title: "状态", dataIndex: "status", width: 110, render: statusTag },
  ]

  if (loading && !diagnostics) {
    return <Skeleton active paragraph={{ rows: 12 }} />
  }

  if (!diagnostics || !summary) {
    return (
      <Card variant="outlined">
        <Empty description="暂无诊断数据">
          <Button icon={<ReloadOutlined />} onClick={() => void loadDiagnostics()}>
            重新加载
          </Button>
        </Empty>
      </Card>
    )
  }

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Card variant="outlined">
        <Row gutter={[16, 16]} align="middle" justify="space-between">
          <Col xs={24} lg={15}>
            <Space orientation="vertical" size={6}>
              <Tag color="blue" icon={<FileSearchOutlined />}>插件诊断</Tag>
              <Title level={3} style={{ margin: 0 }}>插件运行诊断与开通回归中心</Title>
              <Paragraph type="secondary" style={{ margin: 0 }}>
                汇总通知、实名、支付和开通插件的健康状态，集中处理绑定问题、失败实例、待处理实名和密钥风险。
              </Paragraph>
            </Space>
          </Col>
          <Col xs={24} lg="auto">
            <Space wrap>
              <Text type="secondary">更新时间：{formatDate(summary.generated_at)}</Text>
              <Button icon={<ReloadOutlined />} loading={loading} onClick={() => void loadDiagnostics()}>
                刷新
              </Button>
              <Button
                icon={<SyncOutlined />}
                loading={actionLoading === "sync-upstream"}
                onClick={() => runDiagnosticAction("sync-upstream", "同步上游动作", syncAdminUpstreamActions)}
              >
                同步上游
              </Button>
              <Button
                icon={<SyncOutlined />}
                loading={actionLoading === "instance-lifecycle"}
                onClick={() => runDiagnosticAction("instance-lifecycle", "执行生命周期任务", () => runTask("instance_lifecycle"))}
              >
                生命周期巡检
              </Button>
              <Link to="/admin/provision-plugins">
                <Button type="primary" icon={<ApiOutlined />}>开通插件</Button>
              </Link>
            </Space>
          </Col>
        </Row>
      </Card>

      <Alert type={alertType} showIcon title={alertMessage} />

      <Row gutter={[16, 16]}>
        {statItems.map((item) => (
          <Col xs={24} sm={12} xl={5} key={item.title}>
            <Card variant="outlined" style={{ minHeight: 126 }}>
              <Space align="start" style={{ width: "100%", justifyContent: "space-between" }}>
                <Statistic title={item.title} value={item.value} />
                <span style={{ color: item.color, fontSize: 24 }}>{item.icon}</span>
              </Space>
            </Card>
          </Col>
        ))}
      </Row>

      <Tabs
        items={[
          {
            key: "overview",
            label: "总览",
            children: (
              <Space orientation="vertical" size={16} style={{ width: "100%" }}>
                <Card variant="outlined" title="主要问题">
                  <Table
                    size="small"
                    rowKey={(record, index) => `${record.scope}-${record.message}-${index}`}
                    pagination={false}
                    dataSource={diagnostics.warnings}
                    columns={warningColumns}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无问题" /> }}
                  />
                </Card>
                <Card variant="outlined" title="通知与业务通道">
                  <Table
                    size="small"
                    rowKey="type"
                    pagination={false}
                    dataSource={diagnostics.channels}
                    columns={channelColumns}
                    scroll={{ x: 900 }}
                  />
                </Card>
              </Space>
            ),
          },
          {
            key: "notification",
            label: "通知与实名",
            children: (
              <Space orientation="vertical" size={16} style={{ width: "100%" }}>
                <Card variant="outlined" title="插件通道">
                  <Table
                    size="small"
                    rowKey="type"
                    pagination={false}
                    dataSource={diagnostics.channels}
                    columns={channelColumns}
                    scroll={{ x: 900 }}
                  />
                </Card>
                <Card variant="outlined" title="实名处理队列">
                  <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
                    {Object.entries(diagnostics.verification.status_counts).map(([key, value]) => (
                      <Col xs={12} md={6} key={key}>
                        <Statistic title={key} value={value} />
                      </Col>
                    ))}
                  </Row>
                  <Table
                    size="small"
                    rowKey="id"
                    pagination={false}
                    dataSource={diagnostics.verification.processing_records}
                    columns={verificationColumns}
                    scroll={{ x: 900 }}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无待处理记录" /> }}
                  />
                </Card>
              </Space>
            ),
          },
          {
            key: "provision",
            label: "开通回归",
            children: (
              <Space orientation="vertical" size={16} style={{ width: "100%" }}>
                <Card variant="outlined" title="开通插件">
                  <Table
                    size="small"
                    rowKey="id"
                    pagination={false}
                    dataSource={diagnostics.provision.plugins}
                    columns={provisionPluginColumns}
                    scroll={{ x: 850 }}
                  />
                </Card>
                <Card variant="outlined" title="开通接口">
                  <Table
                    size="small"
                    rowKey="id"
                    pagination={false}
                    dataSource={diagnostics.provision.interfaces}
                    columns={interfaceColumns}
                    scroll={{ x: 980 }}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无开通接口" /> }}
                  />
                </Card>
                <Card variant="outlined" title="商品绑定问题">
                  <Table
                    size="small"
                    rowKey="product_id"
                    pagination={{ pageSize: 8 }}
                    dataSource={diagnostics.provision.product_issues}
                    columns={productIssueColumns}
                    scroll={{ x: 900 }}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无商品绑定问题" /> }}
                  />
                </Card>
                <Card variant="outlined" title="最近开通失败">
                  <Table
                    size="small"
                    rowKey="instance_id"
                    pagination={false}
                    dataSource={diagnostics.provision.recent_failures}
                    columns={failureColumns}
                    scroll={{ x: 1100 }}
                    locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无失败实例" /> }}
                  />
                </Card>
              </Space>
            ),
          },
          {
            key: "security",
            label: "安全",
            children: (
              <Card variant="outlined" title="密钥存储检查">
                <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
                  <Col xs={24} sm={8}>
                    <Statistic title="密钥项" value={diagnostics.security.secret_count} />
                  </Col>
                  <Col xs={24} sm={8}>
                    <Statistic title="已加密" value={diagnostics.security.encrypted_secret_count} />
                  </Col>
                  <Col xs={24} sm={8}>
                    <Statistic title="明文风险" value={diagnostics.security.plaintext_secret_count} />
                  </Col>
                </Row>
                <Table
                  size="small"
                  rowKey={(record, index) => `${record.scope}-${record.key}-${record.interface_id || "system"}-${index}`}
                  pagination={{ pageSize: 12 }}
                  dataSource={diagnostics.security.items}
                  columns={secretColumns}
                  scroll={{ x: 800 }}
                />
              </Card>
            ),
          },
        ]}
      />
    </Space>
  )
}
