import { useCallback, useEffect, useMemo, useState } from "react"
import {
  AuditOutlined,
  EyeOutlined,
  ReloadOutlined,
  SearchOutlined,
  SyncOutlined,
} from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Descriptions,
  Empty,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import type { UpstreamActionLog } from "../../api/upstreamActions"
import {
  listAdminUpstreamActions,
  ignoreAdminUpstreamAction,
  markAdminUpstreamActionHandled,
  retryAdminUpstreamAction,
  syncAdminUpstreamAction,
  syncAdminUpstreamActions,
} from "../api/upstream_actions"

const { Title, Paragraph, Text } = Typography

const STATUS_META: Record<string, { label: string; color: string }> = {
  submitted: { label: "已下发", color: "processing" },
  running: { label: "执行中", color: "blue" },
  success: { label: "成功", color: "green" },
  failed: { label: "失败", color: "red" },
  no_task: { label: "已完成", color: "green" },
  manual_handled: { label: "人工已处理", color: "purple" },
  ignored: { label: "无需处理", color: "default" },
  superseded: { label: "已重试", color: "default" },
}

const SOURCE_LABEL: Record<string, string> = {
  manual: "用户手动",
  unsubscribe: "退订",
  lifecycle: "生命周期",
  renewal: "续费",
  retry: "管理员重试",
}

const ACTION_LABEL: Record<string, string> = {
  instance_delete: "强制删除实例",
  instance_suspend: "暂停实例",
  instance_unsuspend: "解除暂停",
  disk_delete: "删除云盘",
  disk_resize_rollback: "回退云盘容量",
  package_instance_rollback: "回退套餐配置",
  package_bandwidth_rollback: "回退带宽配置",
}

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

function statusTag(status: string) {
  const meta = STATUS_META[status] ?? { label: status, color: "default" }
  return <Tag color={meta.color}>{meta.label}</Tag>
}

function jsonText(value: unknown) {
  if (value === null || value === undefined) return "-"
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    return String(value)
  }
}

export default function AdminUpstreamActions() {
  const [items, setItems] = useState<UpstreamActionLog[]>([])
  const [loading, setLoading] = useState(false)
  const [syncing, setSyncing] = useState(false)
  const [keyword, setKeyword] = useState("")
  const [status, setStatus] = useState("")
  const [source, setSource] = useState("")
  const [actionType, setActionType] = useState("")
  const [userId, setUserId] = useState<number | null>(null)
  const [orderId, setOrderId] = useState<number | null>(null)
  const [instanceId, setInstanceId] = useState<number | null>(null)
  const [detail, setDetail] = useState<UpstreamActionLog | null>(null)
  const [actionLoading, setActionLoading] = useState<string | null>(null)

  const loadItems = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listAdminUpstreamActions({
        keyword: keyword.trim() || undefined,
        status: status || undefined,
        source: source || undefined,
        action_type: actionType || undefined,
        user_id: userId ?? undefined,
        order_id: orderId ?? undefined,
        instance_id: instanceId ?? undefined,
        limit: 200,
      })
      setItems(res.data ?? [])
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载资源审计失败")
    } finally {
      setLoading(false)
    }
  }, [actionType, instanceId, keyword, orderId, source, status, userId])

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

  const stats = useMemo(() => {
    return {
      total: items.length,
      running: items.filter((item) => ["submitted", "running"].includes(item.status)).length,
      failed: items.filter((item) => item.status === "failed").length,
      success: items.filter((item) => ["success", "no_task", "manual_handled", "ignored", "superseded"].includes(item.status)).length,
    }
  }, [items])

  const handleSync = async () => {
    setSyncing(true)
    try {
      const res = await syncAdminUpstreamActions()
      const data = res.data
      toast.success(`同步完成：检查 ${data?.checked ?? 0} 条，失败 ${data?.failed ?? 0} 条`)
      await loadItems()
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "同步上游任务失败")
    } finally {
      setSyncing(false)
    }
  }

  const runRowAction = async (
    key: string,
    label: string,
    fn: () => Promise<unknown>,
  ) => {
    setActionLoading(key)
    try {
      await fn()
      toast.success(`${label}已完成`)
      await loadItems()
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || `${label}失败`)
    } finally {
      setActionLoading(null)
    }
  }

  const confirmRetry = (record: UpstreamActionLog) => {
    let remark = ""
    Modal.confirm({
      title: "重试该动作？",
      okText: "确认重试",
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Text type="secondary">系统会按原请求路径和参数重新下发一次。</Text>
          <Input.TextArea
            rows={3}
            maxLength={255}
            showCount
            placeholder="处理备注，可选"
            onChange={(event) => { remark = event.target.value }}
          />
        </Space>
      ),
      onOk: () => runRowAction(
        `retry-${record.id}`,
        "重试",
        () => retryAdminUpstreamAction(record.id, remark.trim() || undefined),
      ),
    })
  }

  const confirmMarkHandled = (record: UpstreamActionLog) => {
    let remark = ""
    Modal.confirm({
      title: "标记人工已处理？",
      okText: "确认",
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Text type="secondary">系统会将该动作视为已完成，并同步更新相关实例本地状态。</Text>
          <Input.TextArea
            rows={3}
            maxLength={255}
            showCount
            placeholder="处理备注，可选"
            onChange={(event) => { remark = event.target.value }}
          />
        </Space>
      ),
      onOk: () => runRowAction(
        `handled-${record.id}`,
        "标记人工已处理",
        () => markAdminUpstreamActionHandled(record.id, remark.trim() || undefined),
      ),
    })
  }

  const confirmIgnore = (record: UpstreamActionLog) => {
    let remark = ""
    Modal.confirm({
      title: "标记无需处理？",
      okText: "确认",
      cancelText: "取消",
      content: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Text type="secondary">该动作会从待处理异常中移除，但不会修改实例本地状态。</Text>
          <Input.TextArea
            rows={3}
            maxLength={255}
            showCount
            placeholder="处理备注，可选"
            onChange={(event) => { remark = event.target.value }}
          />
        </Space>
      ),
      onOk: () => runRowAction(
        `ignore-${record.id}`,
        "标记无需处理",
        () => ignoreAdminUpstreamAction(record.id, remark.trim() || undefined),
      ),
    })
  }

  const columns: TableColumnsType<UpstreamActionLog> = [
    {
      title: "ID",
      dataIndex: "id",
      width: 80,
      render: (value: number) => <Text type="secondary">#{value}</Text>,
    },
    {
      title: "动作",
      dataIndex: "action_type",
      width: 160,
      render: (value: string, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{ACTION_LABEL[value] ?? value}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.request_method} {record.request_path}</Text>
        </Space>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      render: statusTag,
    },
    {
      title: "来源",
      dataIndex: "source",
      width: 110,
      render: (value: string) => <Tag>{SOURCE_LABEL[value] ?? value}</Tag>,
    },
    {
      title: "用户/订单",
      width: 180,
      render: (_, record) => (
        <Space orientation="vertical" size={0}>
          <Text>{record.username || (record.user_id ? `用户 #${record.user_id}` : "-")}</Text>
          {record.order_no ? <Text code style={{ fontSize: 12 }}>{record.order_no}</Text> : null}
        </Space>
      ),
    },
    {
      title: "实例/资源",
      width: 150,
      render: (_, record) => (
        <Space orientation="vertical" size={0}>
          <Text type="secondary">{record.instance_id ? `实例 #${record.instance_id}` : "-"}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.resource_type}{record.resource_id ? ` #${record.resource_id}` : ""}
          </Text>
        </Space>
      ),
    },
    {
      title: "Task ID",
      dataIndex: "upstream_task_id",
      width: 110,
      render: (value: number | null) => value ? <Text code>{value}</Text> : "-",
    },
    {
      title: "错误/备注",
      ellipsis: true,
      render: (_, record) => record.error_message || record.remark || "-",
    },
    {
      title: "时间",
      dataIndex: "created_at",
      width: 170,
      render: fmtDate,
    },
    {
      title: "操作",
      width: 270,
      fixed: "right",
      render: (_, record) => (
        <Space size={6} wrap>
          <Button size="small" icon={<EyeOutlined />} onClick={() => setDetail(record)}>
            详情
          </Button>
          <Button
            size="small"
            icon={<SyncOutlined />}
            loading={actionLoading === `sync-${record.id}`}
            disabled={!record.upstream_task_id}
            onClick={() => runRowAction(`sync-${record.id}`, "同步", () => syncAdminUpstreamAction(record.id))}
          >
            同步
          </Button>
          <Button
            size="small"
            danger
            loading={actionLoading === `retry-${record.id}`}
            disabled={!["failed", "manual_handled", "ignored"].includes(record.status)}
            onClick={() => confirmRetry(record)}
          >
            重试
          </Button>
          <Button
            size="small"
            loading={actionLoading === `handled-${record.id}`}
            disabled={record.status !== "failed"}
            onClick={() => confirmMarkHandled(record)}
          >
            已处理
          </Button>
          <Button
            size="small"
            loading={actionLoading === `ignore-${record.id}`}
            disabled={record.status !== "failed"}
            onClick={() => confirmIgnore(record)}
          >
            忽略
          </Button>
        </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 }}>
            追踪退订、暂停、删除、磁盘回退等上游资源动作的提交和任务结果。
          </Paragraph>
        </Col>
        <Col>
          <Space>
            <Button icon={<SyncOutlined />} loading={syncing} onClick={handleSync}>
              立即同步
            </Button>
            <Button icon={<ReloadOutlined />} loading={loading} onClick={loadItems}>
              刷新
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="当前列表" value={stats.total} suffix="条" prefix={<AuditOutlined />} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="执行中" value={stats.running} suffix="条" styles={{ content: { color: "#1677ff" } }} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="失败待处理" value={stats.failed} suffix="条" styles={{ content: { color: "#cf1322" } }} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="已完成" value={stats.success} suffix="条" styles={{ content: { color: "#389e0d" } }} /></Card>
        </Col>
      </Row>

      <Card variant="outlined">
        <Space orientation="vertical" size={16} style={{ width: "100%" }}>
          <Row gutter={[12, 12]}>
            <Col xs={24} md={8}>
              <Input
                allowClear
                prefix={<SearchOutlined />}
                placeholder="搜索动作 / 路径 / 订单号 / 错误"
                value={keyword}
                onChange={(event) => setKeyword(event.target.value)}
                onPressEnter={loadItems}
              />
            </Col>
            <Col>
              <Select
                value={status}
                onChange={setStatus}
                style={{ width: 130 }}
                options={[
                  { value: "", label: "全部状态" },
                  { value: "submitted", label: "已下发" },
                  { value: "running", label: "执行中" },
                  { value: "success", label: "成功" },
                  { value: "failed", label: "失败" },
                  { value: "no_task", label: "已完成" },
                  { value: "manual_handled", label: "人工已处理" },
                  { value: "ignored", label: "无需处理" },
                  { value: "superseded", label: "已重试" },
                ]}
              />
            </Col>
            <Col>
              <Select
                value={source}
                onChange={setSource}
                style={{ width: 130 }}
                options={[
                  { value: "", label: "全部来源" },
                  { value: "manual", label: "用户手动" },
                  { value: "unsubscribe", label: "退订" },
                  { value: "lifecycle", label: "生命周期" },
                  { value: "renewal", label: "续费" },
                  { value: "retry", label: "管理员重试" },
                ]}
              />
            </Col>
            <Col>
              <Select
                value={actionType}
                onChange={setActionType}
                style={{ width: 170 }}
                options={[
                  { value: "", label: "全部动作" },
                  ...Object.entries(ACTION_LABEL).map(([value, label]) => ({ value, label })),
                ]}
              />
            </Col>
            <Col>
              <InputNumber min={1} precision={0} placeholder="用户 ID" value={userId} onChange={(value) => setUserId(typeof value === "number" ? value : null)} />
            </Col>
            <Col>
              <InputNumber min={1} precision={0} placeholder="订单 ID" value={orderId} onChange={(value) => setOrderId(typeof value === "number" ? value : null)} />
            </Col>
            <Col>
              <InputNumber min={1} precision={0} placeholder="实例 ID" value={instanceId} onChange={(value) => setInstanceId(typeof value === "number" ? value : null)} />
            </Col>
            <Col flex="auto" />
            <Col>
              <Button type="primary" icon={<SearchOutlined />} loading={loading} onClick={loadItems}>
                查询
              </Button>
            </Col>
          </Row>

          <Table
            rowKey="id"
            loading={loading}
            columns={columns}
            dataSource={items}
            pagination={{ pageSize: 12, showSizeChanger: false }}
            scroll={{ x: 1280 }}
            locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无资源操作审计" /> }}
          />
        </Space>
      </Card>

      <Modal
        title="资源操作详情"
        open={!!detail}
        onCancel={() => setDetail(null)}
        footer={<Button onClick={() => setDetail(null)}>关闭</Button>}
        width={860}
      >
        {detail ? (
          <Space orientation="vertical" size={16} style={{ width: "100%" }}>
            <Descriptions column={2} size="small" bordered>
              <Descriptions.Item label="动作">{ACTION_LABEL[detail.action_type] ?? detail.action_type}</Descriptions.Item>
              <Descriptions.Item label="状态">{statusTag(detail.status)}</Descriptions.Item>
              <Descriptions.Item label="用户">{detail.username || detail.user_id || "-"}</Descriptions.Item>
              <Descriptions.Item label="订单">{detail.order_no || detail.order_id || "-"}</Descriptions.Item>
              <Descriptions.Item label="实例">{detail.instance_id || "-"}</Descriptions.Item>
              <Descriptions.Item label="Task ID">{detail.upstream_task_id || "-"}</Descriptions.Item>
              <Descriptions.Item label="请求路径" span={2}>{detail.request_method} {detail.request_path}</Descriptions.Item>
              <Descriptions.Item label="错误" span={2}>{detail.error_message || "-"}</Descriptions.Item>
            </Descriptions>
            <pre style={{ maxHeight: 360, overflow: "auto", margin: 0, padding: 12, background: "#f7f8fa", borderRadius: 6 }}>
{`request:
${jsonText(detail.request_payload)}

response:
${jsonText(detail.response_payload)}

task:
${jsonText(detail.task_payload)}`}
            </pre>
          </Space>
        ) : null}
      </Modal>
    </Space>
  )
}
