import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useUser } from '@/hooks/useUser'
import { useScrollHeight } from '@/hooks/useScrollHeight'
import { listShopCoupon } from '@/api/shop/shopCoupon'
import type { ShopCoupon } from '@/api/shop/shopCoupon/model'
import EmptyState from '@/components/common/EmptyState'

definePageConfig({
  navigationBarTitleText: '领券中心',
})

const CouponCenterPage: React.FC = () => {
  const { isLoggedIn } = useUser()
  const [coupons, setCoupons] = useState<ShopCoupon[]>([])
  const [loading, setLoading] = useState(true)
  const scrollHeight = useScrollHeight(44)


  useEffect(() => {
    if (!isLoggedIn) {
      Taro.navigateTo({ url: '/passport/login' })
      return
    }
    fetchCoupons()
  }, [isLoggedIn])

  const fetchCoupons = async () => {
    try {
      const data = await listShopCoupon({ status: 1 })
      setCoupons(data || [])
    } catch (e) {
      console.error('获取优惠券失败:', e)
    } finally {
      setLoading(false)
    }
  }

  const handleClaimCoupon = (id: number) => {
    Taro.showModal({
      title: '领取优惠券',
      content: '确定要领取这张优惠券吗？',
      success: (res) => {
        if (res.confirm) {
          Taro.showToast({ title: '领取成功', icon: 'success' })
          fetchCoupons()
        }
      },
    })
  }

  const getCouponTypeText = (type: number) => {
    const typeMap: Record<number, string> = {
      1: '无门槛券',
      2: '满减券',
      3: '折扣券',
      4: '运费券',
    }
    return typeMap[type] || '优惠券'
  }

  if (!isLoggedIn) {
    return null
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView scrollY style={{ height: scrollHeight }}>
        {loading ? (
          <View className='flex items-center justify-center py-10'>
            <Text className='text-gray-400'>加载中...</Text>
          </View>
        ) : coupons.length === 0 ? (
          <EmptyState text='暂无可用优惠券' />
        ) : (
          <View className='p-3'>
            {coupons.map((item) => (
              <View
                key={item.id}
                className='bg-white rounded-lg mb-3 overflow-hidden'
              >
                <View className='flex'>
                  <View
                    className='p-4 text-white flex flex-col items-center justify-center'
                    style={{ width: '120px', backgroundColor: '#0e932e' }}
                  >
                    <Text className='text-2xl font-bold'>
                      {item.discountType === 3 ? `${item.discountValue}折` : `¥${item.amount}`}
                    </Text>
                    <Text className='text-xs mt-1'>
                      {item.minAmount ? `满${item.minAmount}可用` : '无门槛'}
                    </Text>
                  </View>
                  <View className='flex-1 p-3'>
                    <Text className='text-sm font-medium text-gray-800 block mb-1'>
                      {getCouponTypeText(item.couponType)}
                    </Text>
                    <Text className='text-xs text-gray-500 mb-1 block'>
                      {item.name}
                    </Text>
                    <Text className='text-xs text-gray-400 block'>
                      有效期至：{item.expireTime}
                    </Text>
                  </View>
                  <View className='flex items-center pr-3'>
                    <View
                      className='px-3 py-1 rounded-full'
                      style={{ backgroundColor: '#0e932e' }}
                      onClick={() => handleClaimCoupon(item.id!)}
                    >
                      <Text className='text-xs text-white'>领取</Text>
                    </View>
                  </View>
                </View>
              </View>
            ))}
          </View>
        )}
      </ScrollView>
    </View>
  )
}

export default CouponCenterPage
