import React, { useState, useEffect } from 'react'
import { View, Text, Image, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listShopGoodsFavorite } from '@/api/shop/shopGoodsFavorite'
import type { ShopGoodsFavorite } from '@/api/shop/shopGoodsFavorite/model'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'
import { getCompressedImageUrl } from '@/utils/image'

definePageConfig({
  navigationBarTitleText: '我的收藏',
})

const FavoriteListPage: React.FC = () => {
  const [list, setList] = useState<ShopGoodsFavorite[]>([])
  const [loading, setLoading] = useState(false)
  const [page, setPage] = useState(1)
  const [finished, setFinished] = useState(false)

  useEffect(() => {
    loadFavorites(1)
  }, [])

  const loadFavorites = async (p: number) => {
    if (loading) return
    setLoading(true)
    try {
      const res = await listShopGoodsFavorite({ page: p, limit: 20 })
      const newList = res || []
      if (p === 1) {
        setList(newList)
      } else {
        setList(prev => [...prev, ...newList])
      }
      setFinished(newList.length < 20)
      setPage(p)
    } catch {
      Taro.showToast({ title: '加载失败', icon: 'none' })
    }
    setLoading(false)
  }

  const handleItemClick = (goodsId: number) => {
    Taro.navigateTo({ url: `/pages/shop/product-detail?id=${goodsId}` })
  }

  const handleLoadMore = () => {
    if (!finished && !loading) {
      loadFavorites(page + 1)
    }
  }

  return (
    <View className='min-h-screen bg-gray-50'>
      <ScrollView
        scrollY
        className='h-screen'
        onScrollToLower={handleLoadMore}
        lowerThreshold={100}
      >
        <View className='p-3'>
          {list.length > 0 ? (
            <View className='grid grid-cols-2 gap-3'>
              {list.map(item => (
                <View
                  key={item.id ?? item.goodsId}
                  className='bg-white rounded-lg overflow-hidden'
                  onClick={() => handleItemClick(item.goodsId!)}
                >
                  <Image
                    className='w-full'
                    style={{ height: '160px' }}
                    src={getCompressedImageUrl(item.goodsImage || item.product?.image || '')}
                    mode='aspectFit'
                  />
                  <View className='p-2'>
                    <Text className='text-sm text-gray-800 line-clamp-2 block'>
                      {item.goodsName || item.product?.name}
                    </Text>
                    <View className='flex flex-row items-baseline gap-1 mt-1'>
                      <Text className='text-red-500 text-sm font-medium'>
                        ¥{item.price || item.salePrice || '0'}
                      </Text>
                      {item.salePrice && Number(item.salePrice) > Number(item.price || 0) ? (
                        <Text className='text-xs text-gray-400 line-through'>
                          ¥{item.salePrice}
                        </Text>
                      ) : null}
                    </View>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            !loading && <EmptyState text='暂无收藏' />
          )}
          <LoadMore loading={loading} finished={finished} />
        </View>
      </ScrollView>
    </View>
  )
}

export default FavoriteListPage
