<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getProductDetailApi } from '@/api/product'
import { addCartItemApi } from '@/api/cart'
import { checkFavoriteApi, addFavoriteApi, cancelFavoriteByProductApi } from '@/api/favorite'
import type { ProductDetail, ProductSku } from '@/types'
import { ShoppingCart, Star, Share, ArrowLeft, Check } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const product = ref<ProductDetail | null>(null)
const selectedSku = ref<ProductSku | null>(null)
const quantity = ref(1)
const loading = ref(false)
const activeImage = ref(0)
const isFavorited = ref(false)

onMounted(async () => {
  loading.value = true
  try {
    const id = Number(route.params.id)
    const detail = await getProductDetailApi(id)
    const fav = await checkFavoriteApi(id).catch(() => false)
    product.value = detail
    isFavorited.value = !!fav
    selectedSku.value = detail.skuList?.[0] ?? null
  } finally {
    loading.value = false
  }
})

function selectSku(sku: ProductSku) {
  selectedSku.value = sku
  quantity.value = 1
}

async function addCart() {
  if (!product.value || !selectedSku.value) return
  await addCartItemApi({
    productId: product.value.id,
    skuId: selectedSku.value.id,
    quantity: quantity.value
  })
  ElMessage.success('已加入购物车')
}

function buyNow() {
  if (!product.value || !selectedSku.value) return
  router.push({
    name: 'order-confirm',
    query: {
      from: 'buyNow',
      productId: String(product.value.id),
      skuId: String(selectedSku.value.id),
      quantity: String(quantity.value)
    }
  })
}

async function toggleFavorite() {
  if (!product.value) return
  if (isFavorited.value) {
    await cancelFavoriteByProductApi(product.value.id)
    isFavorited.value = false
    ElMessage.success('已取消收藏')
  } else {
    await addFavoriteApi(product.value.id)
    isFavorited.value = true
    ElMessage.success('已收藏')
  }
}
</script>

<template>
  <div class="detail-page container">
    <el-skeleton v-if="loading" :rows="10" animated />

    <div v-else-if="product" class="detail-content">
      <!-- Breadcrumb -->
      <el-breadcrumb class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
        <el-breadcrumb-item>{{ product.name }}</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- Main Info -->
      <div class="detail-main">
        <!-- Image Section -->
        <div class="image-section">
          <div class="main-image">
            <img :src="(product.subImages?.[activeImage]) || product.mainImage || 'https://placehold.co/500x500?text=SNACK'" />
          </div>
          <div v-if="product.subImages?.length" class="thumb-list">
            <img
              v-for="(img, idx) in product.subImages" :key="idx"
              :src="img"
              :class="{ active: idx === activeImage }"
              @click="activeImage = idx"
            />
          </div>
        </div>

        <!-- Info Section -->
        <div class="info-section">
          <div class="product-tags">
            <el-tag v-if="product.isHot" type="danger" effect="dark" size="small">热销</el-tag>
            <el-tag v-if="product.isNew" type="success" effect="dark" size="small">新品</el-tag>
          </div>
          <h1 class="product-title">{{ product.name }}</h1>
          <p class="product-subtitle">{{ product.brand || product.categoryName || '' }} · 月销 {{ product.sales }}+</p>

          <div class="price-box">
            <div class="price-main">
              <span class="price-symbol">¥</span>
              <span class="price-value">{{ selectedSku?.price ?? product.minPrice }}</span>
            </div>
            <div class="price-extra">
              <span class="sales">已售 {{ product.sales }} 件</span>
              <span class="views">浏览 {{ product.viewCount }}</span>
            </div>
          </div>

          <div v-if="product.skuList?.length" class="sku-section">
            <span class="section-label">选择规格</span>
            <div class="sku-list">
              <button
                v-for="sku in product.skuList" :key="sku.id"
                class="sku-btn"
                :class="{ active: selectedSku?.id === sku.id }"
                @click="selectSku(sku)"
              >
                {{ sku.skuName }}
                <el-icon v-if="selectedSku?.id === sku.id" class="check-icon"><Check /></el-icon>
              </button>
            </div>
          </div>

          <div class="quantity-section">
            <span class="section-label">购买数量</span>
            <el-input-number v-model="quantity" :min="1" :max="selectedSku?.stock || 99" />
            <span class="stock">库存 {{ selectedSku?.stock ?? 0 }} 件</span>
          </div>

          <div class="action-section">
            <el-button type="primary" size="large" class="action-btn cart-btn" :icon="ShoppingCart" @click="addCart">
              加入购物车
            </el-button>
            <el-button type="danger" size="large" class="action-btn buy-btn" @click="buyNow">
              立即购买
            </el-button>
            <el-button
              :icon="Star"
              circle
              size="large"
              class="fav-btn"
              :class="{ active: isFavorited }"
              @click="toggleFavorite"
            />
          </div>

          <div class="service-tags">
            <span><el-icon><Check /></el-icon> 正品保障</span>
            <span><el-icon><Check /></el-icon> 7天无理由</span>
            <span><el-icon><Check /></el-icon> 极速发货</span>
          </div>
        </div>
      </div>

      <!-- Detail Tabs -->
      <div class="detail-tabs">
        <el-tabs type="border-card" class="custom-tabs">
          <el-tab-pane label="商品详情">
            <div class="detail-html" v-html="product.detail || '<p style=\'color:#999;text-align:center;padding:40px\'>暂无详情</p>'"></div>
          </el-tab-pane>
          <el-tab-pane label="规格参数">
            <el-descriptions :column="2" border class="param-table">
              <el-descriptions-item label="商品名称">{{ product.name }}</el-descriptions-item>
              <el-descriptions-item label="品牌">{{ product.brand || '-' }}</el-descriptions-item>
              <el-descriptions-item label="分类">{{ product.categoryName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="销量">{{ product.sales }}</el-descriptions-item>
              <el-descriptions-item label="浏览量">{{ product.viewCount }}</el-descriptions-item>
              <el-descriptions-item label="重量">{{ selectedSku?.weight ? selectedSku.weight + 'g' : '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<style scoped>
.detail-page {
  padding: 20px 0 60px;
}
.breadcrumb {
  margin-bottom: 24px;
}

/* Detail Main */
.detail-main {
  display: grid;
  grid-template-columns: 460px 1fr;
  gap: 48px;
  background: #fff;
  border-radius: var(--radius-xl);
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
}

/* Image Section */
.image-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.main-image {
  width: 100%;
  aspect-ratio: 1;
  border-radius: var(--radius-lg);
  overflow: hidden;
  border: 1px solid var(--color-border-light);
  background: var(--color-background);
}
.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-slow);
}
.main-image:hover img {
  transform: scale(1.03);
}
.thumb-list {
  display: flex;
  gap: 10px;
}
.thumb-list img {
  width: 68px;
  height: 68px;
  border-radius: var(--radius-md);
  object-fit: cover;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all var(--transition-fast);
  background: var(--color-background);
}
.thumb-list img:hover {
  border-color: var(--color-primary);
}
.thumb-list img.active {
  border-color: var(--color-primary);
  box-shadow: var(--shadow-glow);
}

/* Info Section */
.info-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.product-tags {
  display: flex;
  gap: 8px;
}
.product-title {
  font-size: 26px;
  font-weight: 700;
  line-height: 1.3;
  color: var(--color-text);
}
.product-subtitle {
  color: var(--color-text-muted);
  font-size: 14px;
}
.price-box {
  background: linear-gradient(135deg, #FFF0EB 0%, #FFF7ED 100%);
  padding: 20px 24px;
  border-radius: var(--radius-lg);
  border: 1px solid rgba(255, 107, 53, 0.1);
}
.price-main {
  display: flex;
  align-items: baseline;
  gap: 2px;
}
.price-symbol {
  font-size: 20px;
  color: var(--color-primary);
  font-weight: 600;
}
.price-value {
  font-size: 36px;
  color: var(--color-primary);
  font-weight: 700;
}
.price-extra {
  display: flex;
  gap: 16px;
  margin-top: 8px;
  font-size: 13px;
  color: var(--color-text-muted);
}

/* SKU Section */
.sku-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.section-label {
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text);
}
.sku-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.sku-btn {
  padding: 10px 18px;
  border-radius: var(--radius-md);
  border: 1.5px solid var(--color-border);
  background: #fff;
  color: var(--color-text);
  font-size: 14px;
  cursor: pointer;
  transition: all var(--transition-fast);
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: inherit;
}
.sku-btn:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
}
.sku-btn.active {
  border-color: var(--color-primary);
  background: var(--color-primary-light);
  color: var(--color-primary);
  font-weight: 600;
}
.check-icon {
  font-size: 14px;
}

/* Quantity Section */
.quantity-section {
  display: flex;
  align-items: center;
  gap: 16px;
}
.stock {
  color: var(--color-text-muted);
  font-size: 13px;
}

/* Action Section */
.action-section {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}
.action-btn {
  padding: 0 36px;
  height: 50px;
  border-radius: var(--radius-full);
  font-size: 16px;
  font-weight: 600;
}
.cart-btn {
  background: linear-gradient(135deg, #FFF0EB, #FFF7ED);
  color: var(--color-primary);
  border: 1.5px solid var(--color-primary);
}
.cart-btn:hover {
  background: var(--color-primary-light);
}
.buy-btn {
  background: var(--color-primary-gradient);
  border: none;
}
.fav-btn {
  width: 50px;
  height: 50px;
  border: 1.5px solid var(--color-border);
  color: var(--color-text-muted);
  transition: all var(--transition-fast);
}
.fav-btn:hover {
  border-color: var(--color-danger);
  color: var(--color-danger);
}
.fav-btn.active {
  background: var(--color-danger-light);
  border-color: var(--color-danger);
  color: var(--color-danger);
}

/* Service Tags */
.service-tags {
  display: flex;
  gap: 20px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border-light);
}
.service-tags span {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: var(--color-text-secondary);
}
.service-tags .el-icon {
  color: var(--color-success);
  font-size: 16px;
}

/* Detail Tabs */
.detail-tabs {
  background: #fff;
  border-radius: var(--radius-xl);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
}
.custom-tabs :deep(.el-tabs__header) {
  background: var(--color-background);
  border-bottom: 1px solid var(--color-border-light);
}
.custom-tabs :deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
  padding: 0 24px;
  height: 48px;
}
.detail-html {
  padding: 32px;
  line-height: 1.8;
  min-height: 300px;
}
.detail-html img {
  max-width: 100%;
  border-radius: var(--radius-md);
  margin: 16px 0;
}
.param-table :deep(.el-descriptions__label) {
  background: var(--color-background);
  font-weight: 600;
  width: 120px;
}

/* Responsive */
@media (max-width: 1024px) {
  .detail-main {
    grid-template-columns: 1fr;
    gap: 32px;
  }
}
@media (max-width: 768px) {
  .detail-main {
    padding: 20px;
  }
  .product-title {
    font-size: 20px;
  }
  .action-section {
    flex-wrap: wrap;
  }
  .action-btn {
    flex: 1;
    min-width: 140px;
  }
  .service-tags {
    flex-wrap: wrap;
    gap: 12px;
  }
}
</style>
