import { useCallback, useEffect, useState } from "react"
import { useParams, Link } from "react-router-dom"
import {
  ArrowLeft,
  CheckCircle2,
  Clock,
  XCircle,
  AlertCircle,
  Server,
  Loader2,
  Copy,
  RefreshCw,
} from "lucide-react"
import { PageSkeleton, type SkeletonSpec } from "../utils/skeleton"
import { toast } from "../utils/toast"
import { getOrder, type Order, type OrderInstance } from "../api/orders"

const PAGE_SKELETON: SkeletonSpec[] = [
  { type: "header", title: 200, subtitle: 300 },
  { type: "card", h: 160 },
  { type: "table", rows: 3, cols: 4 },
]

const ORDER_STATUS: Record<string, { label: string; cls: string; icon: typeof CheckCircle2 }> = {
  pending: { label: "待支付", cls: "text-amber-600 bg-amber-50 border-amber-200", icon: Clock },
  paid:    { label: "已支付", cls: "text-emerald-600 bg-emerald-50 border-emerald-200", icon: CheckCircle2 },
  cancelled: { label: "已取消", cls: "text-slate-500 bg-slate-100 border-slate-200", icon: XCircle },
  refunded:  { label: "已退款", cls: "text-purple-600 bg-purple-50 border-purple-200", icon: AlertCircle },
}

const INSTANCE_STATUS: Record<string, { label: string; cls: string; dot: string }> = {
  provisioning:    { label: "开通中", cls: "text-amber-700 bg-amber-50",    dot: "bg-amber-400 animate-pulse" },
  active:          { label: "运行中", cls: "text-emerald-700 bg-emerald-50",  dot: "bg-emerald-500" },
  suspended:       { label: "已暂停", cls: "text-orange-700 bg-orange-50",   dot: "bg-orange-400" },
  terminated:      { label: "已销毁", cls: "text-slate-500 bg-slate-100",    dot: "bg-slate-400" },
  failed:          { label: "开通失败", cls: "text-red-700 bg-red-50",       dot: "bg-red-500" },
  provision_failed: { label: "未开通", cls: "text-red-700 bg-red-50",        dot: "bg-red-500" },
}

function copyText(text: string, label: string) {
  navigator.clipboard.writeText(text).then(() => toast.success(`已复制${label}`))
}

function InstanceCard({ inst }: { inst: OrderInstance }) {
  const meta = INSTANCE_STATUS[inst.status] ?? { label: inst.status, cls: "text-gray-600 bg-gray-100", dot: "bg-gray-400" }
  const isProvisioning = inst.status === "provisioning"

  return (
    <div className="border border-gray-200 rounded-lg p-4 bg-white hover:border-sky-200 transition-colors">
      <div className="flex items-start justify-between gap-4">
        <div className="flex items-center gap-3 min-w-0">
          <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-sky-50 border border-sky-100">
            {isProvisioning
              ? <Loader2 className="w-4 h-4 text-sky-500 animate-spin" />
              : <Server className="w-4 h-4 text-sky-600" />
            }
          </div>
          <div className="min-w-0">
            <p className="text-sm font-medium text-gray-900 truncate">
              {inst.hostname ?? `实例 #${inst.id}`}
            </p>
            <p className="text-xs text-gray-400 mt-0.5">ID: {inst.id}</p>
          </div>
        </div>
        <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium shrink-0 ${meta.cls}`}>
          <span className={`w-1.5 h-1.5 rounded-full ${meta.dot}`} />
          {meta.label}
        </span>
      </div>

      {inst.main_ip && (
        <div className="mt-3 pt-3 border-t border-gray-100 flex flex-wrap gap-x-6 gap-y-1.5">
          <div className="flex items-center gap-2">
            <span className="text-xs text-gray-400">主 IP</span>
            <span className="text-xs font-mono font-medium text-gray-800">{inst.main_ip}</span>
            <button
              onClick={() => copyText(inst.main_ip!, "IP")}
              className="text-gray-300 hover:text-sky-500 transition-colors"
            >
              <Copy className="w-3 h-3" />
            </button>
          </div>
          {inst.expires_at && (
            <div className="flex items-center gap-2">
              <span className="text-xs text-gray-400">到期</span>
              <span className="text-xs text-gray-600">{inst.expires_at.slice(0, 10)}</span>
            </div>
          )}
        </div>
      )}

      {isProvisioning && (
        <p className="mt-3 text-xs text-amber-600 bg-amber-50 rounded px-2.5 py-1.5">
          正在为您开通服务，通常需要 1-3 分钟，完成后将发送邮件通知。
        </p>
      )}
      {inst.status === "failed" && (
        <p className="mt-3 text-xs text-red-600 bg-red-50 rounded px-2.5 py-1.5">
          开通失败，费用已退回至账户余额。如有疑问请联系客服。
        </p>
      )}
      {inst.status === "provision_failed" && (
        <p className="mt-3 text-xs text-red-600 bg-red-50 rounded px-2.5 py-1.5">
          自动开通失败，请稍后重试或联系客服进行手动开通。
        </p>
      )}
    </div>
  )
}

export default function OrderDetail() {
  const { orderId } = useParams<{ orderId: string }>()
  const [order, setOrder] = useState<Order | null>(null)
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)

  const load = useCallback(async (silent = false) => {
    if (!silent) setLoading(true)
    else setRefreshing(true)
    try {
      const res = await getOrder(Number(orderId))
      setOrder(res.data.data ?? null)
    } catch {
      toast.error("订单加载失败")
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [orderId])

  useEffect(() => {
    load()
  }, [load])

  // 有实例在开通中时，每 5 秒自动刷新一次
  useEffect(() => {
    if (!order) return
    const hasProvisioning = order.instances?.some((i) => i.status === "provisioning")
    if (!hasProvisioning) return
    const timer = setInterval(() => load(true), 5000)
    return () => clearInterval(timer)
  }, [load, order])

  const statusMeta = order ? (ORDER_STATUS[order.status] ?? ORDER_STATUS.paid) : ORDER_STATUS.paid
  const StatusIcon = statusMeta.icon

  return (
    <PageSkeleton loading={loading} spec={PAGE_SKELETON}>
      {order && (
        <div className="space-y-6 max-w-4xl mx-auto">
          {/* 顶部导航 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Link
                to="/orders"
                className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-900 transition-colors"
              >
                <ArrowLeft className="w-4 h-4" />
                订单列表
              </Link>
              <span className="text-gray-300">/</span>
              <span className="text-sm text-gray-900 font-medium">{order.out_order_no}</span>
            </div>
            <button
              onClick={() => load(true)}
              disabled={refreshing}
              className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-sky-600 transition-colors disabled:opacity-50"
            >
              <RefreshCw className={`w-3.5 h-3.5 ${refreshing ? "animate-spin" : ""}`} />
              刷新
            </button>
          </div>

          {/* 订单概览卡片 */}
          <div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div>
                <div className="flex items-center gap-3 mb-1">
                  <h1 className="text-lg font-semibold text-gray-900">订单详情</h1>
                  <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${statusMeta.cls}`}>
                    <StatusIcon className="w-3.5 h-3.5" />
                    {statusMeta.label}
                  </span>
                </div>
                <p className="text-sm text-gray-500 font-mono">{order.out_order_no}</p>
                <p className="text-xs text-gray-400 mt-1">{new Date(order.created_at).toLocaleString("zh-CN")}</p>
              </div>
              <div className="text-right">
                <p className="text-xs text-gray-400 mb-1">实付金额</p>
                <div className="flex items-baseline gap-1 justify-end">
                  <span className="text-sm text-gray-500">¥</span>
                  <span className="text-3xl font-semibold text-gray-900">
                    {((order.total_amount - order.discount_amount) / 100).toFixed(2)}
                  </span>
                </div>
                {order.discount_amount > 0 && (
                  <p className="text-xs text-emerald-600 mt-0.5">
                    已优惠 ¥{(order.discount_amount / 100).toFixed(2)}
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* 实例列表 */}
          {order.instances && order.instances.length > 0 && (
            <div>
              <h2 className="text-sm font-semibold text-gray-700 mb-3">
                服务实例
                <span className="ml-2 text-xs font-normal text-gray-400">共 {order.instances.length} 台</span>
              </h2>
              <div className="grid gap-3 sm:grid-cols-2">
                {order.instances.map((inst) => (
                  <InstanceCard key={inst.id} inst={inst} />
                ))}
              </div>
            </div>
          )}

          {/* 商品明细 */}
          {order.items_snapshot && (order.items_snapshot as Record<string, unknown>[]).length > 0 && (
            <div className="bg-white border border-gray-200 rounded-xl overflow-hidden shadow-sm">
              <div className="px-5 py-4 border-b border-gray-100">
                <h2 className="text-sm font-semibold text-gray-700">商品明细</h2>
              </div>
              <div className="divide-y divide-gray-100">
                {(order.items_snapshot as Record<string, unknown>[]).map((snap, i) => (
                  <div key={i} className="px-5 py-3.5 flex items-center justify-between gap-4">
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {snap.product_name as string}
                      </p>
                      <p className="text-xs text-gray-400 mt-0.5">
                        {snap.cycle as string} · x{snap.quantity as number}
                      </p>
                    </div>
                    <p className="text-sm font-medium text-gray-900 shrink-0">
                      ¥{((snap.item_total_cents as number) / 100).toFixed(2)}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </PageSkeleton>
  )
}
