import type { ReactNode } from "react"
import { Badge } from "@/components/ui/badge"
import { ProductCode } from "@/lib/base"

interface SkuCodeBadgeProps {
  productCode: ProductCode
  skuCode: string
}

export function SkuCodeBadge({
  productCode,
  skuCode,
}: SkuCodeBadgeProps): ReactNode {
  switch (productCode) {
    case ProductCode.Short:
    case ProductCode.Long:
      return <ParsedSkuCodeBadge skuCode={skuCode} />
    default:
      return <Badge variant="outline">{skuCode}</Badge>
  }
}

function ParsedSkuCodeBadge({ skuCode }: { skuCode: string }): ReactNode {
  const params = new URLSearchParams(skuCode)
  const modeStr = params.get("mode")

  let mode: string | undefined
  let modeClass: string | undefined
  switch (modeStr) {
    case "time":
      mode = "包时"
      modeClass = "bg-green-50"
      break
    case "quota":
      mode = "包量"
      modeClass = "bg-blue-50"
      break
  }

  const live = params.get("live")
  const expire = params.get("expire")

  if (!mode || !live || !expire) {
    return (
      <Badge variant="secondary" className="bg-red-50">
        {skuCode}（解析失败）
      </Badge>
    )
  }

  return (
    <div className="flex flex-wrap gap-1">
      <Badge variant="secondary" className={modeClass}>
        类型：{mode}
      </Badge>
      <Badge variant="secondary">有效时间：{live} 分钟</Badge>
      {expire !== "0" && (
        <Badge variant="secondary">过期时间：{expire} 天</Badge>
      )}
    </div>
  )
}
