import { useEffect, useMemo, useState } from "react"
import { useNavigate } from "react-router-dom"
import { BorderOutlined, CheckSquareOutlined, ThunderboltOutlined } from "@ant-design/icons"
import { Alert, Button, Col, Empty, Modal, Row, Space, Spin, Tag, Typography } from "antd"
import { toast } from "../../utils/toast"
import { listProducts, createProduct, type ConfigField, type Product } from "../api/product"

const { Text } = Typography

interface Props {
  open: boolean
  onClose: () => void
  groupId?: number | null
}

const SPECS = [
  { vcpu: 1,  memory: "1GB",  label: "1C1G"   },
  { vcpu: 2,  memory: "2GB",  label: "2C2G"   },
  { vcpu: 2,  memory: "4GB",  label: "2C4G"   },
  { vcpu: 4,  memory: "4GB",  label: "4C4G"   },
  { vcpu: 4,  memory: "8GB",  label: "4C8G"   },
  { vcpu: 8,  memory: "8GB",  label: "8C8G"   },
  { vcpu: 8,  memory: "12GB", label: "8C12G"  },
  { vcpu: 12, memory: "12GB", label: "12C12G" },
  { vcpu: 12, memory: "16GB", label: "12C16G" },
  { vcpu: 8,  memory: "16GB", label: "8C16G"  },
  { vcpu: 16, memory: "16GB", label: "16C16G" },
  { vcpu: 16, memory: "32GB", label: "16C32G" },
  { vcpu: 32, memory: "32GB", label: "32C32G" },
]

// 从产品名称中提取前缀（去掉末尾的规格部分）
function extractNamePrefix(name: string): string {
  // 匹配末尾的规格模式，如 "4C8G", "4H8G", "4核8G" 等
  const cleaned = name.replace(/[\s\-_]*\d+[CHch核][×x*]?\d+[GgBb]+\s*$/i, "").trim()
  return cleaned || ""
}

function buildProductName(prefix: string, specLabel: string): string {
  if (!prefix) return specLabel
  return `${prefix}-${specLabel}`
}

function parseMemoryToMb(value: string): number | null {
  const text = value.trim().toLowerCase()
  const match = text.match(/^(\d+(?:\.\d+)?)\s*(g|gb|m|mb)?$/)
  if (!match) return null
  const amount = Number(match[1])
  if (!Number.isFinite(amount)) return null
  const unit = match[2] ?? "mb"
  return unit === "g" || unit === "gb" ? Math.round(amount * 1024) : Math.round(amount)
}

function syncSpecConfig(config: ConfigField[] | null, spec: { vcpu: number; memory: string }) {
  if (!config) return config
  const next = config.map((field) => ({ ...field }))
  upsertFixed(next, "cpu", "CPU核心数", String(spec.vcpu))
  const memoryMb = parseMemoryToMb(spec.memory)
  if (memoryMb !== null) upsertFixed(next, "memory", "内存(MB)", String(memoryMb))
  return next
}

function upsertFixed(config: ConfigField[], key: string, label: string, value: string) {
  const found = config.find((field) => String(field.def || "").split("|", 1)[0].trim() === key)
  if (found) {
    found.def = found.def || `${key}|${label}`
    found.type = "fixed"
    found.value = value
    return
  }
  config.push({ def: `${key}|${label}`, type: "fixed", value })
}

export default function ProductBatchCreateModal({ open, onClose, groupId }: Props) {
  const navigate = useNavigate()
  const [step, setStep] = useState<1 | 2>(1)
  const [allProducts, setAllProducts] = useState<Product[]>([])
  const [loadingProducts, setLoadingProducts] = useState(false)
  const [templateId, setTemplateId] = useState<number | null>(null)
  const [selectedSpecs, setSelectedSpecs] = useState<Set<string>>(new Set())
  const [creating, setCreating] = useState(false)

  useEffect(() => {
    if (!open) return
    setStep(1)
    setTemplateId(null)
    setSelectedSpecs(new Set())
    if (!groupId) {
      setAllProducts([])
      toast.error("请先选择一个产品组")
      return
    }
    setLoadingProducts(true)
    listProducts(groupId)
      .then((res) => setAllProducts(res.data ?? []))
      .catch(() => toast.error("加载产品列表失败"))
      .finally(() => setLoadingProducts(false))
  }, [groupId, open])

  const template = useMemo(
    () => allProducts.find((p) => p.id === templateId) ?? null,
    [allProducts, templateId]
  )

  const namePrefix = useMemo(
    () => (template ? extractNamePrefix(template.name) : ""),
    [template]
  )

  const toggleSpec = (label: string) => {
    setSelectedSpecs((prev) => {
      const next = new Set(prev)
      if (next.has(label)) next.delete(label)
      else next.add(label)
      return next
    })
  }

  const toggleAll = () => {
    if (selectedSpecs.size === SPECS.length) setSelectedSpecs(new Set())
    else setSelectedSpecs(new Set(SPECS.map((s) => s.label)))
  }

  const handleCreate = async () => {
    if (!template) return
    if (selectedSpecs.size === 0) {
      toast.error("请至少选择一个规格")
      return
    }
    setCreating(true)
    const results: { spec: string; product: Product | null; error: string | null }[] = []
    for (const spec of SPECS.filter((s) => selectedSpecs.has(s.label))) {
      try {
        const res = await createProduct({
          group_id: template.group_id,
          sku: `${template.sku}-${spec.label.toLowerCase()}`,
          name: buildProductName(namePrefix, spec.label),
          type: template.type,
          status: template.status,
          vcpu: spec.vcpu,
          memory: spec.memory,
          cpu_model: template.cpu_model,
          cpu_base_mhz: template.cpu_base_mhz,
          cpu_turbo_mhz: template.cpu_turbo_mhz,
          disk: template.disk,
          bandwidth: template.bandwidth,
          features: template.features,
          badges: template.badges,
          base_setup_fee: template.base_setup_fee,
          base_price: template.base_price,
          stock_policy: template.stock_policy,
          stock: template.stock,
          min_quantity: template.min_quantity,
          max_quantity: template.max_quantity,
          auto_provision: template.auto_provision,
          trial_enabled: template.trial_enabled,
          trial_days: template.trial_days,
          sort_order: template.sort_order,
          is_featured: template.is_featured,
          cloud_server_id: template.cloud_server_id,
          api_type: template.api_type,
          api_identifier: template.api_identifier,
          provision_config: syncSpecConfig(template.provision_config, spec),
          // 不复制定价，保持新产品使用默认价格配置。
        })
        results.push({ spec: spec.label, product: res.data ?? null, error: null })
      } catch (e: unknown) {
        const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
        results.push({ spec: spec.label, product: null, error: detail ?? "创建失败" })
      }
    }
    setCreating(false)
    onClose()
    navigate("/admin/products", {
      state: { batchCreateResults: results, templateName: template.name },
    })
  }

  return (
    <Modal
      open={open}
      destroyOnHidden
      title="一键配置产品"
      width={680}
      onCancel={onClose}
      footer={
        step === 1 ? (
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button
              type="primary"
              disabled={!templateId}
              onClick={() => setStep(2)}
            >
              下一步：选择规格
            </Button>
          </Space>
        ) : (
          <Row justify="space-between" style={{ width: "100%" }}>
            <Col><Button onClick={() => setStep(1)}>上一步</Button></Col>
            <Col>
              <Space>
                <Button onClick={onClose}>取消</Button>
              <Button
                type="primary"
                icon={<ThunderboltOutlined />}
                loading={creating}
                disabled={creating || selectedSpecs.size === 0}
                onClick={handleCreate}
              >
                {creating ? `创建中…` : `创建 ${selectedSpecs.size} 个产品`}
              </Button>
              </Space>
            </Col>
          </Row>
        )
      }
    >
      {step === 1 ? (
        <Space orientation="vertical" size={16} style={{ width: "100%" }}>
          <Alert
            type="info"
            showIcon
            title="选择模板产品"
            description="新产品将复制模板产品的配置，只替换 CPU 和内存；价格周期请在下一页批量设置。"
          />
          <Spin spinning={loadingProducts}>
            {allProducts.length === 0 ? (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前产品组暂无可用模板" />
            ) : (
              <div style={{ maxHeight: 360, overflowY: "auto" }}>
                {allProducts.map((p) => {
                  const selected = templateId === p.id
                  return (
                    <div
                      key={p.id}
                      onClick={() => setTemplateId(p.id)}
                      style={{
                        cursor: "pointer",
                        padding: "12px 16px",
                        border: selected ? "1px solid #1677ff" : "1px solid #f0f0f0",
                        borderRadius: 8,
                        marginBottom: 8,
                        background: selected ? "#e6f4ff" : "#fff",
                      }}
                    >
                      <Space orientation="vertical" size={4}>
                        <Space><Text strong>{p.name}</Text>{selected && <Tag color="blue">已选</Tag>}</Space>
                        <Text type="secondary">
                          {p.vcpu != null ? `${p.vcpu}核` : "—"} · {p.memory ?? "—"} · SKU: {p.sku}
                        </Text>
                      </Space>
                    </div>
                  )
                })}
              </div>
            )}
          </Spin>
        </Space>
      ) : (
        <Space orientation="vertical" size={16} style={{ width: "100%" }}>
          <Alert
            type="success"
            showIcon
            title={<span>模板：{template?.name}</span>}
            description={
              namePrefix ? (
                <span>生成名称前缀：{namePrefix}</span>
              ) : (
                <span>未识别到名称前缀，将直接使用规格名作为产品名。</span>
              )
            }
          />
          <Row justify="space-between" align="middle">
            <Col><Text type="secondary">选择要生成的规格，已选 {selectedSpecs.size} 个。</Text></Col>
            <Col>
              <Button size="small" onClick={toggleAll}>
                {selectedSpecs.size === SPECS.length ? "取消全选" : "全选"}
              </Button>
            </Col>
          </Row>
          <Row gutter={[8, 8]}>
            {SPECS.map((spec) => {
              const checked = selectedSpecs.has(spec.label)
              const productName = buildProductName(namePrefix, spec.label)
              return (
                <Col xs={12} sm={8} key={spec.label}>
                  <Button
                    block
                    type={checked ? "primary" : "default"}
                    icon={checked ? <CheckSquareOutlined /> : <BorderOutlined />}
                    onClick={() => toggleSpec(spec.label)}
                    style={{ height: "auto", justifyContent: "flex-start", padding: "10px 12px" }}
                  >
                    <Space orientation="vertical" size={0} align="start">
                      <Text style={{ color: checked ? "#fff" : undefined }}>{spec.label}</Text>
                      <Text type={checked ? undefined : "secondary"} style={{ color: checked ? "rgba(255,255,255,.82)" : undefined, fontSize: 12 }}>
                        {productName}
                      </Text>
                    </Space>
                  </Button>
                </Col>
              )
            })}
          </Row>
        </Space>
      )}
    </Modal>
  )
}
