import { useCallback, useEffect, useState } from "react"
import { useNavigate, useParams } from "react-router-dom"
import { ArrowLeftOutlined, ReloadOutlined } from "@ant-design/icons"
import { Button, Col, Row, Space, Tag, Typography } from "antd"
import { PageSkeleton, type SkeletonSpec } from "../../utils/skeleton"
import { toast } from "../../utils/toast"
import ProductFormBody from "../components/ProductFormBody"
import { getProduct, type Product } from "../api/product"
import { listGroups, type ProductGroup } from "../api/product_catalog"
import { listCloudServers, type CloudServer } from "../api/cloud_server"

const PAGE_SKELETON: SkeletonSpec[] = [
  { type: "header", title: 220, subtitle: 320 },
  { type: "card", h: 520 },
]

const { Title, Text } = Typography

const STATUS_LABEL: Record<Product["status"], string> = {
  active: "在售",
  draft: "草稿",
  hidden: "隐藏",
  deprecated: "停售",
}

export default function AdminProductEdit() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const productId = Number(id)

  const [loading, setLoading] = useState(true)
  const [product, setProduct] = useState<Product | null>(null)
  const [groups, setGroups] = useState<ProductGroup[]>([])
  const [cloudServers, setCloudServers] = useState<CloudServer[]>([])

  const reload = useCallback(
    async (silent = false) => {
      if (!Number.isFinite(productId) || productId <= 0) {
        toast.error("无效的产品 ID")
        navigate("/admin/products")
        return
      }
      if (!silent) setLoading(true)
      try {
        const [pRes, gRes, csRes] = await Promise.all([
          getProduct(productId),
          listGroups(undefined, { includeOsOptions: false }),
          listCloudServers(),
        ])
        setProduct(pRes.data ?? null)
        setGroups(gRes.data ?? [])
        setCloudServers(csRes.data ?? [])
      } catch (e: unknown) {
        const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
        toast.error(detail || "加载失败")
      } finally {
        setLoading(false)
      }
    },
    [productId, navigate],
  )

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

  return (
    <PageSkeleton loading={loading} spec={PAGE_SKELETON} gap={24}>
      <Space orientation="vertical" size={20} style={{ width: "100%" }}>
        <Row gutter={[16, 16]} align="bottom" justify="space-between">
          <Col flex="auto">
            <Space orientation="vertical" size={8}>
              <Button icon={<ArrowLeftOutlined />} onClick={() => navigate("/admin/products")}>
                返回产品列表
              </Button>
              <Title level={3} style={{ margin: 0 }}>{product?.name ?? "编辑产品"}</Title>
              {product ? (
                <Space wrap>
                  <Text code>{product.sku}</Text>
                  <Tag>{STATUS_LABEL[product.status]}</Tag>
                </Space>
              ) : (
                <Text type="secondary">加载中...</Text>
              )}
            </Space>
          </Col>
          <Col>
            <Button icon={<ReloadOutlined />} onClick={() => reload()}>
              刷新
            </Button>
          </Col>
        </Row>

        {product && (
          <ProductFormBody
            key={product.updated_at}
            initial={product}
            groups={groups}
            cloudServers={cloudServers}
            onSaved={(p) => setProduct(p)}
            onDeleted={() => navigate("/admin/products")}
            onGroupUpdated={(g) =>
              setGroups((prev) => prev.map((x) => (x.id === g.id ? g : x)))
            }
          />
        )}
      </Space>
    </PageSkeleton>
  )
}
