import React, { useState, useEffect } from 'react'
import { View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { listShopSigninRecord, addShopSigninRecord } from '@/api/shop/shopSigninRecord'

definePageConfig({
  navigationBarTitleText: '每日签到',
})

const SigninPage: React.FC = () => {
  const { user, isLoggedIn } = useUser()
  const [signedDates, setSignedDates] = useState<string[]>([])
  const [todaySigned, setTodaySigned] = useState(false)
  const [loading, setLoading] = useState(false)

  const today = new Date()
  const todayStr = today.toISOString().split('T')[0] // YYYY-MM-DD

  // 获取当月已签到日期
  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    loadSignedRecords()
  }, [isLoggedIn])

  const loadSignedRecords = async () => {
    try {
      const year = today.getFullYear()
      const month = today.getMonth() + 1
      const data = await listShopSigninRecord({
        userId: (user as any)?.userId,
        year,
        month,
      })
      if (data && Array.isArray(data)) {
        const dates = data.map((record: any) => record.signinDate)
        setSignedDates(dates)
        setTodaySigned(dates.includes(todayStr))
      }
    } catch (err) {
      console.error('加载签到记录失败', err)
    }
  }

  const handleSignin = async () => {
    if (todaySigned) {
      Taro.showToast({ title: '今日已签到', icon: 'none' })
      return
    }
    if (loading) return

    setLoading(true)
    try {
      await addShopSigninRecord({
        userId: (user as any)?.userId,
        signinDate: todayStr,
      })
      Taro.showToast({ title: '签到成功 +5积分', icon: 'success' })
      setTodaySigned(true)
      setSignedDates(prev => [...prev, todayStr])
    } catch (err: any) {
      console.error('签到失败', err)
      Taro.showToast({ title: err.message || '签到失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  // 生成本周日期列表（用于UI显示）
  const getWeekDates = () => {
    const dates = []
    for (let i = 6; i >= 0; i--) {
      const d = new Date(today)
      d.setDate(d.getDate() - i)
      dates.push(d)
    }
    return dates
  }
  const weekDates = getWeekDates()

  const getDayOfWeek = (date: Date) => {
    const days = ['日', '一', '二', '三', '四', '五', '六']
    return days[date.getDay()]
  }

  return (
    <View className='min-h-screen bg-gray-50 p-4'>
      {/* 签到卡片 */}
      <View className='bg-white rounded-xl p-6 text-center'>
        <Text className='text-lg font-bold text-gray-800 block mb-1'>每日签到</Text>
        <Text className='text-sm text-gray-500 block mb-4'>连续签到获得更多积分</Text>

        {/* 本周签到 */}
        <View className='grid grid-cols-7 gap-1 mb-4'>
          {weekDates.map((date, idx) => {
            const dateStr = date.toISOString().split('T')[0]
            const dayOfWeek = getDayOfWeek(date)
            const isSigned = signedDates.includes(dateStr)
            const isToday = dateStr === todayStr
            return (
              <View key={idx} className='flex flex-col items-center py-2'>
                <Text className='text-xs text-gray-400 mb-1'>周{dayOfWeek}</Text>
                <View
                  className={`w-8 h-8 rounded-full flex items-center justify-center ${
                    isSigned
                      ? 'bg-green-500'
                      : isToday
                      ? 'bg-green-50 border border-green-500'
                      : 'bg-gray-50'
                  }`}
                >
                  <Text className={`text-xs ${isSigned ? 'text-white' : isToday ? 'text-green-600' : 'text-gray-400'}`}>
                    {date.getDate()}
                  </Text>
                </View>
              </View>
            )
          })}
        </View>

        <View
          className='py-2 rounded-full'
          style={{ backgroundColor: todaySigned ? '#ccc' : '#0e932e' }}
          onClick={handleSignin}
        >
          <Text className='text-white font-medium text-sm'>
            {loading ? '签到中...' : todaySigned ? '已签到' : '立即签到'}
          </Text>
        </View>
      </View>

      {/* 签到规则 */}
      <View className='bg-white rounded-xl p-4 mt-4'>
        <Text className='text-sm font-medium text-gray-800 mb-2'>签到规则</Text>
        <View className='text-xs text-gray-500 leading-6'>
          <Text className='block'>1. 每日签到可获得 5 积分</Text>
          <Text className='block'>2. 连续签到 7 天额外奖励 20 积分</Text>
          <Text className='block'>3. 连续签到 30 天额外奖励 100 积分</Text>
          <Text className='block'>4. 中断签到后连续天数重新计算</Text>
        </View>
      </View>
    </View>
  )
}

export default SigninPage
