import { Tag } from "antd"
import { toast } from "../../utils/toast"
import type { ServerDetail, UpstreamTask } from "../../api/servers"

export const UNSUPPORTED_OPERATION_MESSAGE = "对接产品不支持该操作"
export const FINANCE_TICKET_MESSAGE = "该对接产品需要通过财务工单处理"

export const TASK_TERMINAL = new Set([2, 3, 4, 5])

export const TASK_STATUS: Record<number, { label: string; color: string }> = {
  0: { label: "未开始", color: "default" },
  1: { label: "执行中", color: "processing" },
  2: { label: "成功", color: "success" },
  3: { label: "失败", color: "error" },
  4: { label: "强制结束", color: "warning" },
  5: { label: "已取消", color: "default" },
}

export const TASK_TYPE: Record<string, string> = {
  on: "开机",
  off: "关机",
  hardoff: "强制关机",
  reboot: "重启",
  password: "重置密码",
  rebuild: "重装系统",
  resize: "变更配置",
  suspend: "暂停",
  unsuspend: "解除暂停",
  delete: "删除实例",
}

export const TAB_LABELS = [
  { key: "info", label: "信息与监控" },
  { key: "monitor", label: "监控记录" },
  { key: "nat", label: "转发管理" },
  { key: "disk", label: "弹性云盘" },
  { key: "backup", label: "备份还原" },
  { key: "firewall", label: "防火墙规则" },
  { key: "reinstall", label: "重装系统" },
  { key: "upgrade", label: "套餐升级" },
  { key: "renewal", label: "续费" },
  { key: "refund", label: "退订管理" },
]

export const CYCLE_LABEL: Record<string, string> = {
  monthly: "月付",
  quarterly: "季付",
  semiannually: "半年付",
  semi_annually: "半年付",
  annually: "年付",
  yearly: "年付",
  biennially: "两年付",
  triennially: "三年付",
  one_time: "一次性",
}

const SERVER_STATUS: Record<string, { label: string; color: string }> = {
  provisioning: { label: "开通中", color: "processing" },
  active: { label: "运行中", color: "success" },
  suspended: { label: "已暂停", color: "warning" },
  terminated: { label: "已销毁", color: "default" },
  failed: { label: "开通失败", color: "error" },
  provision_failed: { label: "待处理", color: "error" },
}

export function copyText(text: string | null | undefined, label: string) {
  if (!text) return
  navigator.clipboard.writeText(text).then(() => toast.success(`已复制${label}`))
}

export function formatMemory(mb: number | null) {
  if (!mb) return "-"
  return mb >= 1024 ? `${(mb / 1024).toFixed(mb % 1024 === 0 ? 0 : 1)} GB` : `${mb} MB`
}

export function formatDate(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,
  })
}

export function formatCycle(value: string | null | undefined) {
  if (!value) return "-"
  return CYCLE_LABEL[value] ?? value
}

export function formatMoney(cents: number | null | undefined) {
  return `￥${((cents ?? 0) / 100).toFixed(2)}`
}

export function resolveDisplayStatus(status: string, upstreamPower?: string | null) {
  if (status && status !== "active") {
    return SERVER_STATUS[status] ?? { label: status || "未知", color: "default" }
  }

  if (upstreamPower) {
    const normalized = upstreamPower.toLowerCase()
    const isOff = normalized === "off" || normalized.includes("off") || upstreamPower.includes("关")
    const isOn = normalized === "on" || upstreamPower.includes("开") || upstreamPower.includes("运行")

    if (isOff) return { label: "已关机", color: "default" }
    if (isOn) return { label: "运行中", color: "success" }
    return { label: upstreamPower, color: "processing" }
  }

  return SERVER_STATUS[status] ?? { label: status || "未知", color: "default" }
}

export function statusTag(status: string, upstreamPower?: string | null) {
  const meta = resolveDisplayStatus(status, upstreamPower)
  return <Tag color={meta.color}>{meta.label}</Tag>
}

export function inferPowerFromTasks(tasks: UpstreamTask[]) {
  const latestPowerTask = tasks.find((task) => task.status === 2 && ["on", "off", "hardoff", "reboot"].includes(task.type))
  if (!latestPowerTask) return null
  if (latestPowerTask.type === "off" || latestPowerTask.type === "hardoff") return "off"
  return "on"
}

export function isZjmfFinanceServer(server: ServerDetail | null | undefined) {
  return server?.api_type === "zjmf_finance" || server?.upstream?.provider === "zjmf_finance"
}

export const PLUGIN_TAB_LABELS = [
  { key: "info", label: "面板管理" },
  { key: "renewal", label: "续费" },
  { key: "refund", label: "退订管理" },
]

export function isPluginServer(server: ServerDetail | null | undefined) {
  return server?.api_type === "plugin" || !!server?.provision_plugin
}

export function networkLabel(server: ServerDetail) {
  if (server.main_ip) return server.main_ip
  if (isZjmfFinanceServer(server)) return "未返回公网 IP"
  const values = [server.nat_acl_limit, server.nat_web_limit]
    .filter((value): value is number => typeof value === "number")
  if (values.some((value) => value >= 0)) return "NAT网络"
  if (values.length > 0 && values.every((value) => value === -1)) return "无网络"
  return "-"
}
