<template>
  <view class="followed-shops-page">
    <view class="header">
      <text class="header-title">我关注的店铺</text>
    </view>

    <view class="shop-list" v-if="shops.length > 0">
      <view class="shop-item" v-for="shop in shops" :key="shop.id" @click="goToShop(shop)">
        <image :src="shop.shop_logo != null ? shop.shop_logo : '/static/images/default.png'" class="shop-logo" mode="aspectFill" />
        <view class="shop-info">
          <text class="shop-name">{{ shop.shop_name }}</text>
          <text class="shop-desc">{{ shop.description != null ? shop.description : '暂无介绍' }}</text>
          <view class="shop-meta">
             <text class="rating shop-meta-text">⭐ {{ shop.rating_avg }}</text>
             <text class="sales shop-meta-text">销量: {{ shop.total_sales }}</text>
          </view>
        </view>
        <button class="unfollow-btn" @click.stop="unfollow(shop)">已关注</button>
      </view>
    </view>
    
    <view v-else-if="loading == false" class="empty-state">
      <text class="empty-text">暂无关注的店铺</text>
      <button class="go-shop-btn" @click="goHome">去逛逛</button>
    </view>
    
    <view v-if="loading" class="loading-state">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import { supabaseService } from '@/utils/supabaseService.uts'

type FollowedShop = {
    id: string
    merchant_id: string
    shop_name: string
    shop_logo: string | null
    description: string | null
    rating_avg: number
    total_sales: number
}

const shops = ref<Array<FollowedShop>>([])
const loading = ref<boolean>(true)

const loadFollowedShops = async (): Promise<void> => {
    loading.value = true
    const userId = supabaseService.getCurrentUserId()
    if (userId == null || userId == '') {
        uni.navigateTo({ url: '/pages/auth/login' })
        return
    }

    const res = await supabaseService.getFollowedShops(userId)
    
    const list: Array<FollowedShop> = []
    if (res != null && Array.isArray(res)) {
        for (let i: number = 0; i < res.length; i++) {
            const item = res[i] as UTSJSONObject
            const shopDataRaw = item.get('ml_shops')
            if (shopDataRaw != null) {
                const shopData = shopDataRaw as UTSJSONObject
                const shop: FollowedShop = {
                    id: shopData.getString('id') ?? '',
                    merchant_id: shopData.getString('merchant_id') ?? '',
                    shop_name: shopData.getString('shop_name') ?? '',
                    shop_logo: shopData.getString('shop_logo'),
                    description: shopData.getString('description'),
                    rating_avg: shopData.getNumber('rating_avg') ?? 5.0,
                    total_sales: shopData.getNumber('total_sales') ?? 0
                } as FollowedShop
                list.push(shop)
            }
        }
    }
    
    shops.value = list
    loading.value = false
}

const doUnfollow = async (shopId: string, userId: string): Promise<void> => {
    const success = await supabaseService.unfollowShop(shopId, userId)
    if (success) {
        uni.showToast({ title: '已取消', icon: 'none' })
        loadFollowedShops()
    } else {
        uni.showToast({ title: '操作失败', icon: 'none' })
    }
}

const unfollow = async (shop: FollowedShop): Promise<void> => {
    const userId = supabaseService.getCurrentUserId()
    if (userId == null || userId == '') return

    uni.showModal({
        title: '提示',
        content: '确定取消关注该店铺吗？',
        success: (res) => {
            if (res.confirm) {
                doUnfollow(shop.id, userId)
            }
        }
    })
}

const goToShop = (shop: FollowedShop): void => {
    const targetId = shop.merchant_id != '' ? shop.merchant_id : shop.id
    uni.navigateTo({
        url: `/pages/mall/consumer/shop-detail?merchantId=${targetId}`
    })
}

const goHome = (): void => {
    uni.switchTab({ url: '/pages/main/index' })
}

onMounted(() => {
    loadFollowedShops()
})
</script>

<style>
.followed-shops-page {
  padding: 15px;
  background-color: #f5f5f5;
  flex: 1;
}
.header {
  margin-bottom: 15px;
}
.header-title {
  font-size: 18px;
  font-weight: bold;
}
.shop-list {
  display: flex;
  flex-direction: column;
}
.shop-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
}
.shop-item:last-child {
  margin-bottom: 0;
}
.shop-logo {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  background-color: #eee;
  margin-right: 12px;
}
.shop-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.shop-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.shop-desc {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.shop-meta {
  font-size: 10px;
  color: #999;
  margin-top: 4px;
  display: flex;
}
.shop-meta-text {
  margin-right: 8px;
}
.unfollow-btn {
  font-size: 12px;
  padding: 4px 12px;
  background-color: #eee;
  color: #666;
  border-radius: 20px;
  margin-left: 10px;
}
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100px;
}
.empty-text {
  color: #999;
  margin-bottom: 20px;
}
.go-shop-btn {
  background-color: #ff4444;
  color: white;
  padding: 8px 24px;
  border-radius: 20px;
  font-size: 14px;
}
.loading-state {
    text-align: center;
    padding-top: 50px;
    color: #999;
}
</style>
