<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { userApi } from "../../api/user";
import { tenantPath } from "../../utils/tenant";

const wallet = ref({ balance: 0, points: 0 });
const couponCount = ref(0);
const recentOrders = ref([]);
const route = useRoute();
const tenantRoute = (path) => tenantPath(path, route);

const statusColor = (status) => {
  const map = {
    created: "text-orange-600",
    paid: "text-blue-600",
    completed: "text-green-600",
    refunding: "text-purple-600",
    refunded: "text-slate-500",
    cancelled: "text-slate-400",
  };
  return map[status] || "text-slate-500";
};

const fetchData = async () => {
  // Fetch Wallet
  userApi
    .getWallet()
    .then((w) => {
      wallet.value.balance = w.balance || 0;
    })
    .catch((e) => console.error("Wallet fetch failed:", e));

  // Fetch User Info (Points)
  userApi
    .getMe()
    .then((u) => {
      wallet.value.points = u.points || 0;
    })
    .catch((e) => console.error("Me fetch failed:", e));

  // Fetch Coupons
  userApi
    .getCoupons("unused")
    .then((c) => {
      couponCount.value = (c || []).length;
    })
    .catch((e) => console.error("Coupons fetch failed:", e));

  // Fetch Recent Orders
  userApi
    .getOrders("all")
    .then((o) => {
      recentOrders.value = (o || []).slice(0, 3);
    })
    .catch((e) => console.error("Orders fetch failed:", e));
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <!-- Stat Cards -->
      <router-link
        :to="tenantRoute('/me/wallet')"
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-100 flex items-center gap-4 hover:shadow-md hover:border-primary-100 transition-all cursor-pointer"
      >
        <div
          class="w-12 h-12 rounded-full bg-blue-50 text-blue-600 flex items-center justify-center text-xl"
        >
          <i class="pi pi-wallet"></i>
        </div>
        <div>
          <div class="text-sm text-slate-500">账户余额</div>
          <div class="text-2xl font-bold text-slate-900">
            ¥ {{ wallet.balance }}
          </div>
        </div>
        <i
          class="pi pi-chevron-right ml-auto text-slate-300 group-hover:text-primary-400"
        ></i>
      </router-link>
      <div
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-100 flex items-center gap-4 hover:shadow-md hover:border-primary-100 transition-all cursor-pointer group active:scale-[0.98]"
      >
        <div
          class="w-12 h-12 rounded-full bg-yellow-50 text-yellow-600 flex items-center justify-center text-xl transition-transform group-hover:scale-110"
        >
          <i class="pi pi-star"></i>
        </div>
        <div>
          <div class="text-sm text-slate-500">我的积分</div>
          <div class="text-2xl font-bold text-slate-900">
            {{ wallet.points }}
          </div>
        </div>
        <i
          class="pi pi-chevron-right ml-auto text-slate-300 group-hover:text-primary-400"
        ></i>
      </div>
      <div
        class="bg-white p-6 rounded-xl shadow-sm border border-slate-100 flex items-center gap-4 hover:shadow-md hover:border-primary-100 transition-all cursor-pointer group active:scale-[0.98]"
      >
        <div
          class="w-12 h-12 rounded-full bg-red-50 text-red-600 flex items-center justify-center text-xl transition-transform group-hover:scale-110"
        >
          <i class="pi pi-ticket"></i>
        </div>
        <div>
          <div class="text-sm text-slate-500">优惠券</div>
          <div class="text-2xl font-bold text-slate-900">
            {{ couponCount }} 张
          </div>
        </div>
        <i
          class="pi pi-chevron-right ml-auto text-slate-300 group-hover:text-primary-400"
        ></i>
      </div>
    </div>

    <!-- Recent Orders -->
    <div class="mt-8 bg-white rounded-xl shadow-sm border border-slate-100 p-6">
      <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-bold text-slate-900">最近订单</h2>
        <router-link
          :to="tenantRoute('/me/orders')"
          class="text-sm text-primary-600 hover:text-primary-700 font-medium px-2 py-1 rounded hover:bg-primary-50 transition-colors"
          >查看全部 <i class="pi pi-angle-right"></i
        ></router-link>
      </div>

      <div class="space-y-4">
        <div
          v-for="order in recentOrders"
          :key="order.id"
          @click="$router.push(tenantRoute(`/me/orders/${order.id}`))"
          class="flex items-center gap-4 p-4 border border-slate-100 rounded-lg hover:border-primary-100 hover:shadow-sm transition-all cursor-pointer active:scale-[0.99] group"
        >
          <div
            class="w-16 h-16 bg-slate-100 rounded flex-shrink-0 flex items-center justify-center relative overflow-hidden"
          >
            <template v-if="order.type === 'recharge' || !order.items?.length">
              <i class="pi pi-wallet text-2xl text-primary-500"></i>
            </template>
            <img
              v-else-if="order.items && order.items.length > 0"
              :src="order.items[0].cover"
              class="w-full h-full object-cover rounded transition-transform group-hover:scale-105"
            />
            <i v-else class="pi pi-box text-2xl text-slate-400"></i>
          </div>
          <div class="flex-1 min-w-0">
            <h3
              class="font-bold text-slate-900 truncate group-hover:text-primary-600 transition-colors"
            >
              {{
                order.type === "recharge" || !order.items?.length
                  ? "账户充值"
                  : order.items?.[0]?.title || "未知商品"
              }}
            </h3>
            <div class="text-sm text-slate-500 mt-1">
              {{ order.create_time }} · 订单号: {{ order.id }}
            </div>
          </div>
          <div class="text-right">
            <div class="font-bold text-slate-900">¥ {{ order.amount }}</div>
            <div
              class="text-sm mt-1 font-medium"
              :class="statusColor(order.status)"
            >
              {{ order.status_description }}
            </div>
          </div>
        </div>
        <div
          v-if="recentOrders.length === 0"
          class="text-center text-slate-400 py-4"
        >
          暂无订单
        </div>
      </div>
    </div>

    <!-- Recent Views (Mock) -->
    <div class="mt-8 bg-white rounded-xl shadow-sm border border-slate-100 p-6">
      <div class="flex items-center justify-between mb-6">
        <h2 class="text-xl font-bold text-slate-900">最近浏览</h2>
        <button class="text-sm text-slate-500 hover:text-slate-700">
          <i class="pi pi-trash"></i> 清空历史
        </button>
      </div>
      <div
        class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4"
      >
        <div class="text-center text-slate-400 col-span-full py-8">
          暂无浏览记录
        </div>
      </div>
    </div>
  </div>
</template>
