<template>
  <view class="red-packets-page">
    <view class="tab-header" style="position: fixed; top: 0; left: 0; right: 0; z-index: 10;">
      <text 
        class="tab-item" 
        :class="{ active: currentTab === 0 }" 
        @click="currentTab = 0">未使用</text>
      <text 
        class="tab-item" 
        :class="{ active: currentTab === 1 }" 
        @click="currentTab = 1">已使用/过期</text>
    </view>

    <view v-if="loading" class="loading-state">
      <text>加载中...</text>
    </view>

    <scroll-view v-else class="packet-list" direction="vertical">
        <view v-if="filteredPackets.length === 0" class="empty-state">
            <text class="empty-text">暂无相关红包</text>
        </view>
        <view v-else v-for="item in filteredPackets" :key="item.id" class="packet-item" :class="{ disabled: item.status !== 0 }">
            <view class="packet-left">
                <text class="packet-amount">¥<text class="amount-num">{{ item.amount }}</text></text>
                <text class="packet-condition">无门槛</text>
            </view>
            <view class="packet-right">
                <view class="packet-info">
                    <text class="packet-name">{{ item.name }}</text>
                    <text class="packet-date">有效期至 {{ formatTime(item.expire_at) }}</text>
                </view>
                <view class="packet-action">
                    <button v-if="item.status === 0" class="use-btn" @click="usePacket(item)">立即使用</button>
                    <text v-else class="status-text">{{ getStatusText(item.status) }}</text>
                </view>
            </view>
        </view>
    </scroll-view>
  </view>
</template>

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

type RedPacket = {
  id: string
  user_id: string
  amount: number
  name: string
  status: number // 0: unused, 1: used, 2: expired
  expire_at: string
  created_at: string
}

const loading = ref(true)
const currentTab = ref(0)
const packets = ref<Array<RedPacket>>([])

const filteredPackets = computed((): Array<RedPacket> => {
    const result: Array<RedPacket> = []
    if (currentTab.value === 0) {
        for (let i: number = 0; i < packets.value.length; i++) {
            if (packets.value[i].status === 0) {
                result.push(packets.value[i])
            }
        }
    } else {
        for (let i: number = 0; i < packets.value.length; i++) {
            if (packets.value[i].status !== 0) {
                result.push(packets.value[i])
            }
        }
    }
    return result
})

const loadData = async () => {
    loading.value = true
    try {
        const rawList = await supabaseService.getUserRedPackets()
        const mappedList: Array<RedPacket> = []
        for (let i: number = 0; i < rawList.length; i++) {
            const item = rawList[i] as UTSJSONObject
            const packet: RedPacket = {
                id: item.getString('id') ?? '',
                user_id: '',
                amount: item.getNumber('amount') ?? 0,
                name: item.getString('name') ?? '',
                status: item.getNumber('status') ?? 0,
                expire_at: item.getString('expire_at') ?? '',
                created_at: item.getString('created_at') ?? ''
            } as RedPacket
            mappedList.push(packet)
        }
        packets.value = mappedList
    } catch (e) {
        console.error(e)
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    loadData()
})

const usePacket = (item: RedPacket) => {
    uni.switchTab({
        url: '/pages/main/index'
    })
}

const getStatusText = (status: number): string => {
    if (status === 1) return '已使用'
    if (status === 2) return '已过期'
    return ''
}

const formatTime = (timeStr: string): string => {
  if (timeStr == '') return '永久有效'
  const date = new Date(timeStr)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}
</script>

<style>
.red-packets-page {
  background-color: #f5f5f5;
  flex: 1;
}

.tab-header {
  display: flex;
  background-color: #fff;
  padding: 10px 0;
  /* position: sticky is removed in flavor of inline fixed style */
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #666;
  padding-bottom: 8px;
  border-bottom: 2px solid transparent;
}

.tab-item.active {
  color: #ff5000;
  border-bottom-color: #ff5000;
  font-weight: bold;
}

.packet-list {
  flex: 1;
  padding: 15px;
}

.packet-item {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.packet-item.disabled .packet-left,
.packet-item.disabled .packet-name,
.packet-item.disabled .amount-num {
  color: #999;
  background-color: #f0f0f0;
}

.packet-item.disabled .packet-left {
  background-color: #e0e0e0;
}

.packet-left {
  width: 100px;
  background-color: #fff5f0;
  color: #ff5000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
}

.packet-amount {
  font-size: 14px;
}

.amount-num {
  font-size: 28px;
  font-weight: bold;
}

.packet-condition {
  font-size: 12px;
  margin-top: 4px;
}

.packet-right {
  flex: 1;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.packet-info {
  display: flex;
  flex-direction: column;
}

.packet-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.packet-date {
  font-size: 12px;
  color: #999;
}

.use-btn {
  font-size: 12px;
  background-color: #ff5000;
  color: #fff;
  border-radius: 15px;
  padding: 4px 12px;
  line-height: 1.5;
}

.status-text {
    font-size: 14px;
    color: #999;
}

.loading-state, .empty-state {
  padding: 40px;
  align-items: center;
  justify-content: center;
  display: flex;
}
</style>