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'

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.favoriteId}
                  className='bg-white rounded-lg overflow-hidden'
                  onClick={() => handleItemClick(item.goodsId!)}
                >
                  <Image
                    className='w-full'
                    style={{ height: '160px' }}
                    src={item.goodsImage}
                    mode='aspectFill'
                  />
                  <View className='p-2'>
                    <Text className='text-sm text-gray-800 line-clamp-2 block'>
                      {item.goodsName}
                    </Text>
                    <Text className='text-red-500 text-sm font-medium mt-1 block'>
                      ¥{item.salePrice || '0'}
                    </Text>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            !loading && <EmptyState text='暂无收藏' />
          )}
          <LoadMore loading={loading} finished={finished} />
        </View>
      </ScrollView>
    </View>
  )
}

export default FavoriteListPage
