<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { CartItem } from '@/types'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import { Delete, ArrowRight, ShoppingCart, Minus, Plus, Check, Warning } from '@element-plus/icons-vue'

const router = useRouter()
const cartStore = useCartStore()

const selectedAll = computed({
  get: () => cartStore.allSelected === 1,
  set: (val: boolean) => cartStore.toggleAllSelected(val)
})

async function onQuantityChange(item: { skuId: number; quantity: number }, val: number | undefined) {
  if (val) await cartStore.updateQuantity(item.skuId, val)
}

async function onSelectChange(item: { skuId: number; selected: number }) {
  await cartStore.toggleItemSelected(item.skuId, item.selected === 1 ? 0 : 1)
}

async function removeItem(skuId: number) {
  await ElMessageBox.confirm('确定从购物车删除该商品吗？', '提示', { type: 'warning' })
  await cartStore.removeItem(skuId)
  ElMessage.success('已删除')
}

async function clearAll() {
  await ElMessageBox.confirm('确定清空购物车吗？', '提示', { type: 'warning' })
  await cartStore.clear()
  ElMessage.success('已清空')
}

function goCheckout() {
  if (cartStore.selectedCount === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  router.push('/order-confirm')
}

function increment(item: CartItem) {
  const max = item.stock || 99
  if (item.quantity < max) {
    onQuantityChange(item, item.quantity + 1)
  }
}

function decrement(item: CartItem) {
  if (item.quantity > 1) {
    onQuantityChange(item, item.quantity - 1)
  }
}

onMounted(() => {
  cartStore.fetchCart()
})
</script>

<template>
  <div class="cart-page container">
    <div class="page-header">
      <h1 class="page-title">
        <span class="title-icon">
          <el-icon :size="28"><ShoppingCart /></el-icon>
        </span>
        购物车
      </h1>
      <span v-if="cartStore.items.length > 0" class="item-count">
        共 {{ cartStore.items.length }} 件商品
      </span>
    </div>

    <!-- Empty State -->
    <div v-if="!cartStore.loading && cartStore.items.length === 0" class="empty-state">
      <div class="empty-box">
        <div class="empty-icon">
          <el-icon :size="64"><ShoppingCart /></el-icon>
        </div>
        <h3>购物车空空如也</h3>
        <p>快去挑选心仪的零食吧 ~</p>
        <el-button type="primary" size="large" class="empty-btn" @click="router.push('/')">
          去逛逛
        </el-button>
      </div>
    </div>

    <!-- Cart Layout -->
    <div v-else class="cart-layout">
      <!-- Left: Product List -->
      <div class="cart-left">
        <div class="list-header">
          <el-checkbox v-model="selectedAll" size="default">
            <span class="select-text">全选</span>
          </el-checkbox>
          <el-button link type="danger" size="small" @click="clearAll">
            <el-icon><Delete /></el-icon> 清空
          </el-button>
        </div>

        <div class="product-list">
          <div
            v-for="item in cartStore.items"
            :key="item.skuId"
            class="product-item"
            :class="{ selected: item.selected === 1 }"
          >
            <div class="item-check">
              <el-checkbox :model-value="item.selected === 1" @change="onSelectChange(item)" />
            </div>

            <div class="item-image" @click="router.push({ name: 'product-detail', params: { id: item.productId } })">
              <img :src="item.productImage || 'https://placehold.co/200x200?text=SNACK'" />
            </div>

            <div class="item-info">
              <h4 class="item-name" @click="router.push({ name: 'product-detail', params: { id: item.productId } })">
                {{ item.productName }}
              </h4>
              <p class="item-sku">{{ item.skuName }}</p>
              <div class="item-price-row">
                <span class="price">¥{{ item.price }}</span>
                <span v-if="item.stock && item.stock <= 5" class="stock-warning">
                  <el-icon><Warning /></el-icon> 仅剩 {{ item.stock }} 件
                </span>
              </div>
            </div>

            <div class="item-actions">
              <div class="quantity-control">
                <button class="qty-btn" :disabled="item.quantity <= 1" @click="decrement(item)">
                  <el-icon><Minus /></el-icon>
                </button>
                <span class="qty-value">{{ item.quantity }}</span>
                <button class="qty-btn" :disabled="item.quantity >= (item.stock || 99)" @click="increment(item)">
                  <el-icon><Plus /></el-icon>
                </button>
              </div>
              <div class="item-subtotal">
                <span class="sub-label">小计</span>
                <span class="sub-price">¥{{ item.subtotal }}</span>
              </div>
              <button class="delete-btn" @click="removeItem(item.skuId)">
                <el-icon><Delete /></el-icon>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Right: Checkout Panel -->
      <div class="cart-right">
        <div class="checkout-panel">
          <h3 class="panel-title">结算明细</h3>

          <div class="panel-body">
            <div class="line-item">
              <span>商品总额</span>
              <span>¥{{ cartStore.selectedAmount.toFixed(2) }}</span>
            </div>
            <div class="line-item">
              <span>运费</span>
              <span class="free">免运费</span>
            </div>
            <div class="line-item">
              <span>优惠</span>
              <span>¥0.00</span>
            </div>
            <div class="divider"></div>
            <div class="line-item total">
              <span>实付金额</span>
              <span class="total-price">¥{{ cartStore.selectedAmount.toFixed(2) }}</span>
            </div>
          </div>

          <div class="panel-footer">
            <div class="selected-info">
              <el-icon v-if="cartStore.selectedCount > 0" class="check-icon"><Check /></el-icon>
              已选 <strong>{{ cartStore.selectedCount }}</strong> 件商品
            </div>
            <el-button
              type="primary"
              size="large"
              class="checkout-btn"
              :disabled="cartStore.selectedCount === 0"
              @click="goCheckout"
            >
              去结算 <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cart-page {
  padding: 24px 0 60px;
}

/* Page Header */
.page-header {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  margin-bottom: 24px;
}
.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 26px;
  font-weight: 700;
  margin: 0;
}
.title-icon {
  width: 44px;
  height: 44px;
  border-radius: var(--radius-md);
  background: var(--color-primary-gradient);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  box-shadow: var(--shadow-md);
}
.item-count {
  font-size: 14px;
  color: var(--color-text-muted);
}

/* Empty State */
.empty-state {
  display: flex;
  justify-content: center;
  padding: 60px 0;
}
.empty-box {
  background: #fff;
  border-radius: var(--radius-xl);
  padding: 80px 60px;
  text-align: center;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  max-width: 480px;
  width: 100%;
}
.empty-icon {
  width: 100px;
  height: 100px;
  border-radius: var(--radius-full);
  background: var(--color-primary-light);
  color: var(--color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24px;
}
.empty-box h3 {
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 8px;
  color: var(--color-text);
}
.empty-box p {
  color: var(--color-text-muted);
  margin-bottom: 28px;
}
.empty-btn {
  padding: 0 48px;
  height: 46px;
  border-radius: var(--radius-full);
  font-size: 16px;
  font-weight: 600;
}

/* Cart Layout */
.cart-layout {
  display: grid;
  grid-template-columns: 1fr 340px;
  gap: 24px;
  align-items: start;
}

/* Left: Product List */
.cart-left {
  background: #fff;
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  overflow: hidden;
}
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--color-border-light);
  background: var(--color-background);
}
.select-text {
  font-size: 14px;
  color: var(--color-text-secondary);
  margin-left: 6px;
}

/* Product Item */
.product-list {
  padding: 8px 0;
}
.product-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  border-bottom: 1px solid var(--color-border-light);
  transition: all var(--transition-fast);
  position: relative;
}
.product-item:last-child {
  border-bottom: none;
}
.product-item:hover {
  background: var(--color-background);
}
.product-item.selected {
  background: linear-gradient(90deg, var(--color-primary-light) 0%, transparent 60%);
}

.item-check {
  flex-shrink: 0;
}
.item-image {
  width: 100px;
  height: 100px;
  border-radius: var(--radius-md);
  overflow: hidden;
  flex-shrink: 0;
  cursor: pointer;
  border: 1px solid var(--color-border-light);
  background: var(--color-background);
}
.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-base);
}
.item-image:hover img {
  transform: scale(1.05);
}

.item-info {
  flex: 1;
  min-width: 0;
}
.item-name {
  font-size: 15px;
  font-weight: 600;
  color: var(--color-text);
  margin-bottom: 6px;
  cursor: pointer;
  line-height: 1.4;
  transition: color var(--transition-fast);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.item-name:hover {
  color: var(--color-primary);
}
.item-sku {
  font-size: 13px;
  color: var(--color-text-muted);
  margin-bottom: 10px;
}
.item-price-row {
  display: flex;
  align-items: center;
  gap: 12px;
}
.price {
  font-size: 18px;
  font-weight: 700;
  color: var(--color-primary);
}
.stock-warning {
  font-size: 12px;
  color: var(--color-warning);
  display: flex;
  align-items: center;
  gap: 4px;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-shrink: 0;
}

/* Quantity Control */
.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  overflow: hidden;
}
.qty-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: #fff;
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
  font-size: 12px;
}
.qty-btn:hover:not(:disabled) {
  background: var(--color-primary-light);
  color: var(--color-primary);
}
.qty-btn:disabled {
  color: var(--color-border);
  cursor: not-allowed;
}
.qty-value {
  width: 40px;
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text);
  border-left: 1px solid var(--color-border);
  border-right: 1px solid var(--color-border);
  height: 32px;
  line-height: 32px;
}

.item-subtotal {
  text-align: right;
  min-width: 80px;
}
.sub-label {
  font-size: 12px;
  color: var(--color-text-muted);
  display: block;
  margin-bottom: 2px;
}
.sub-price {
  font-size: 18px;
  font-weight: 700;
  color: var(--color-primary);
}

.delete-btn {
  width: 32px;
  height: 32px;
  border-radius: var(--radius-full);
  border: none;
  background: transparent;
  color: var(--color-text-muted);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}
.delete-btn:hover {
  background: var(--color-danger-light);
  color: var(--color-danger);
}

/* Right: Checkout Panel */
.cart-right {
  position: sticky;
  top: 100px;
}
.checkout-panel {
  background: #fff;
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-light);
  overflow: hidden;
}
.panel-title {
  font-size: 16px;
  font-weight: 700;
  padding: 20px 24px;
  border-bottom: 1px solid var(--color-border-light);
  margin: 0;
}
.panel-body {
  padding: 20px 24px;
}
.line-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 14px;
  color: var(--color-text-secondary);
}
.line-item.total {
  font-size: 15px;
  font-weight: 600;
  color: var(--color-text);
  padding-top: 12px;
}
.total-price {
  font-size: 28px;
  font-weight: 700;
  color: var(--color-primary);
}
.divider {
  height: 1px;
  background: var(--color-border-light);
  margin: 8px 0;
}
.free {
  color: var(--color-success);
  font-weight: 600;
}

.panel-footer {
  padding: 16px 24px 24px;
  border-top: 1px solid var(--color-border-light);
}
.selected-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: var(--color-text-secondary);
  margin-bottom: 12px;
}
.selected-info strong {
  color: var(--color-primary);
}
.check-icon {
  color: var(--color-success);
}
.checkout-btn {
  width: 100%;
  height: 48px;
  border-radius: var(--radius-full);
  font-size: 16px;
  font-weight: 600;
}

/* Responsive */
@media (max-width: 1024px) {
  .cart-layout {
    grid-template-columns: 1fr;
  }
  .cart-right {
    position: static;
  }
  .checkout-panel {
    max-width: 400px;
    margin-left: auto;
  }
}
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 8px;
  }
  .product-item {
    flex-wrap: wrap;
    gap: 12px;
    padding: 16px;
  }
  .item-image {
    width: 80px;
    height: 80px;
  }
  .item-info {
    flex: 1;
    min-width: 140px;
  }
  .item-actions {
    width: 100%;
    justify-content: space-between;
    padding-left: 28px;
  }
  .checkout-panel {
    max-width: 100%;
  }
}
</style>
