<template>
  <view class="signin-page">
    <view class="header">
      <view class="header-content">
        <text class="title">每日签到</text>
        <text class="subtitle">连续签到可获得额外奖励</text>
      </view>
      <view class="points-display">
        <text class="points-label">当前积分</text>
        <text class="points-value">{{ totalPoints }}</text>
      </view>
    </view>

    <view class="calendar-section">
      <view class="calendar-header">
        <view class="month-nav">
          <text class="nav-btn" @click="prevMonth">&lt;</text>
          <text class="current-month">{{ currentYear }}年{{ currentMonth }}月</text>
          <text class="nav-btn" @click="nextMonth">&gt;</text>
        </view>
        <view class="continuous-info">
          <text class="continuous-label">已连续签到</text>
          <text class="continuous-value">{{ continuousDays }}天</text>
        </view>
      </view>

      <view class="calendar-weekdays">
        <text class="weekday" v-for="day in weekdays" :key="day">{{ day }}</text>
      </view>

      <view class="calendar-days">
        <view 
          v-for="(day, index) in calendarDays" 
          :key="index" 
          class="day-cell"
          :class="{ 
            'empty': day.day === 0,
            'signed': day.signed,
            'today': day.isToday
          }"
        >
          <text v-if="day.day > 0" class="day-number">{{ day.day }}</text>
          <view v-if="day.signed" class="signed-mark">
            <text class="check-icon">✓</text>
          </view>
        </view>
      </view>
    </view>

    <view class="signin-btn-section">
      <button 
        class="signin-btn" 
        :class="{ 'signed-today': signedToday }"
        :disabled="signedToday"
        @click="doSignin"
      >
        {{ signedToday ? '今日已签到' : '立即签到' }}
      </button>
    </view>

    <view class="rules-section">
      <text class="section-title">签到规则</text>
      <view class="rule-list">
        <view class="rule-item">
          <text class="rule-icon">📅</text>
          <text class="rule-text">每日签到可获得5积分</text>
        </view>
        <view class="rule-item">
          <text class="rule-icon">🔥</text>
          <text class="rule-text">连续签到7天额外奖励20积分</text>
        </view>
        <view class="rule-item">
          <text class="rule-icon">🏆</text>
          <text class="rule-text">连续签到30天额外奖励100积分</text>
        </view>
        <view class="rule-item">
          <text class="rule-icon">⚠️</text>
          <text class="rule-text">中断签到后连续天数将重置</text>
        </view>
      </view>
    </view>

    <view class="signin-popup" v-if="showPopup" @click="closePopup">
      <view class="popup-content" @click.stop>
        <view class="popup-icon">🎉</view>
        <text class="popup-title">签到成功</text>
        <view class="popup-points">
          <text class="popup-points-label">获得积分</text>
          <text class="popup-points-value">+{{ popupPoints }}</text>
        </view>
        <view class="popup-bonus" v-if="popupBonus > 0">
          <text class="popup-bonus-label">连续签到奖励</text>
          <text class="popup-bonus-value">+{{ popupBonus }}</text>
        </view>
        <view class="popup-continuous">
          <text>已连续签到 {{ popupContinuousDays }} 天</text>
        </view>
        <button class="popup-btn" @click="closePopup">确定</button>
      </view>
    </view>
  </view>
</template>

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

type CalendarDay = {
  day: number
  signed: boolean
  isToday: boolean
}

const totalPoints = ref<number>(0)
const continuousDays = ref<number>(0)
const signedToday = ref<boolean>(false)
const currentYear = ref<number>(new Date().getFullYear())
const currentMonth = ref<number>(new Date().getMonth() + 1)
const signinRecords = ref<string[]>([])
const showPopup = ref<boolean>(false)
const popupPoints = ref<number>(0)
const popupBonus = ref<number>(0)
const popupContinuousDays = ref<number>(0)

const weekdays: string[] = ['日', '一', '二', '三', '四', '五', '六']

const calendarDays = computed((): CalendarDay[] => {
  const days: CalendarDay[] = []
  const year = currentYear.value
  const month = currentMonth.value
  
  const firstDay = new Date(year, month - 1, 1).getDay()
  const daysInMonth = new Date(year, month, 0).getDate()
  
  const today = new Date()
  const todayStr = today.toISOString().split('T')[0]
  
  for (let i = 0; i < firstDay; i++) {
    days.push({ day: 0, signed: false, isToday: false })
  }
  
  for (let i = 1; i <= daysInMonth; i++) {
    const dateStr = `${year}-${month.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`
    const isToday = dateStr === todayStr
    const signed = signinRecords.value.includes(dateStr)
    days.push({ day: i, signed, isToday })
  }
  
  return days
})

const loadSigninData = async (): Promise<void> => {
  uni.showLoading({ title: '加载中...' })
  
  try {
    const points = await supabaseService.getUserPoints()
    totalPoints.value = points
    
    const status = await supabaseService.getTodaySigninStatus()
    signedToday.value = status.getBoolean('signed') ?? false
    continuousDays.value = status.getNumber('continuous_days') ?? 0
    
    const records = await supabaseService.getSigninRecords(currentYear.value, currentMonth.value)
    const dates: string[] = []
    for (let i = 0; i < records.length; i++) {
      const record = records[i]
      let dateStr = ''
      if (record instanceof UTSJSONObject) {
        dateStr = record.getString('signin_date') ?? ''
      } else {
        const rObj = JSON.parse(JSON.stringify(record)) as UTSJSONObject
        dateStr = rObj.getString('signin_date') ?? ''
      }
      if (dateStr !== '') {
        dates.push(dateStr)
      }
    }
    signinRecords.value = dates
  } catch (e) {
    console.error('加载签到数据失败:', e)
  } finally {
    uni.hideLoading()
  }
}

const doSignin = async (): Promise<void> => {
  if (signedToday.value) return
  
  uni.showLoading({ title: '签到中...' })
  
  try {
    const result = await supabaseService.signin()
    
    if (result.getBoolean('success') === true) {
      popupPoints.value = result.getNumber('points') ?? 0
      popupBonus.value = result.getNumber('bonus_points') ?? 0
      popupContinuousDays.value = result.getNumber('continuous_days') ?? 0
      totalPoints.value = result.getNumber('total_points') ?? 0
      continuousDays.value = popupContinuousDays.value
      signedToday.value = true
      
      const today = new Date().toISOString().split('T')[0]
      signinRecords.value.push(today)
      
      showPopup.value = true
    } else {
      const message = result.getString('message') ?? '签到失败'
      uni.showToast({ title: message, icon: 'none' })
    }
  } catch (e) {
    console.error('签到异常:', e)
    uni.showToast({ title: '签到异常', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

const closePopup = (): void => {
  showPopup.value = false
}

const prevMonth = (): void => {
  if (currentMonth.value === 1) {
    currentYear.value--
    currentMonth.value = 12
  } else {
    currentMonth.value--
  }
  loadSigninData()
}

const nextMonth = (): void => {
  if (currentMonth.value === 12) {
    currentYear.value++
    currentMonth.value = 1
  } else {
    currentMonth.value++
  }
  loadSigninData()
}

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

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

.header {
  background: linear-gradient(135deg, #ff6b35 0%, #ff8c42 100%);
  padding: 20px 16px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  flex-direction: column;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.subtitle {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 4px;
}

.points-display {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 10px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.points-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.points-value {
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.calendar-section {
  background-color: white;
  margin: 12px;
  border-radius: 12px;
  padding: 16px;
}

.calendar-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.month-nav {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.nav-btn {
  font-size: 18px;
  color: #666;
  padding: 4px 12px;
}

.current-month {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 8px;
}

.continuous-info {
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: #fff5f0;
  padding: 4px 12px;
  border-radius: 16px;
}

.continuous-label {
  font-size: 12px;
  color: #ff6b35;
}

.continuous-value {
  font-size: 14px;
  font-weight: bold;
  color: #ff6b35;
  margin-left: 4px;
}

.calendar-weekdays {
  display: flex;
  flex-direction: row;
  margin-bottom: 8px;
}

.weekday {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #999;
  padding: 8px 0;
}

.calendar-days {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.day-cell {
  width: 14.28%;
  height: 45px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.day-cell.empty {
  background-color: transparent;
}

.day-number {
  font-size: 14px;
  color: #333;
}

.day-cell.today .day-number {
  color: #ff6b35;
  font-weight: bold;
}

.day-cell.signed {
  background-color: #fff5f0;
  border-radius: 8px;
}

.signed-mark {
  position: absolute;
  bottom: 2px;
  width: 16px;
  height: 16px;
  background-color: #ff6b35;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  font-size: 10px;
  color: white;
}

.signin-btn-section {
  padding: 16px;
}

.signin-btn {
  background: linear-gradient(135deg, #ff6b35 0%, #ff8c42 100%);
  color: white;
  font-size: 18px;
  font-weight: bold;
  border-radius: 24px;
  height: 48px;
  line-height: 48px;
}

.signin-btn.signed-today {
  background: #ccc;
}

.rules-section {
  background-color: white;
  margin: 12px;
  border-radius: 12px;
  padding: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.rule-list {
  display: flex;
  flex-direction: column;
}

.rule-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 8px 0;
}

.rule-icon {
  font-size: 16px;
  margin-right: 8px;
}

.rule-text {
  font-size: 14px;
  color: #666;
}

.signin-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.popup-content {
  background-color: white;
  border-radius: 16px;
  padding: 24px;
  width: 280px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.popup-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.popup-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.popup-points {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 8px;
}

.popup-points-label {
  font-size: 14px;
  color: #666;
}

.popup-points-value {
  font-size: 24px;
  font-weight: bold;
  color: #ff6b35;
  margin-left: 8px;
}

.popup-bonus {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 8px;
}

.popup-bonus-label {
  font-size: 14px;
  color: #666;
}

.popup-bonus-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff6b35;
  margin-left: 8px;
}

.popup-continuous {
  font-size: 14px;
  color: #999;
  margin-bottom: 16px;
}

.popup-btn {
  background-color: #ff6b35;
  color: white;
  font-size: 16px;
  border-radius: 20px;
  width: 100%;
  height: 40px;
  line-height: 40px;
}
</style>
