import React, { useState, useEffect } from 'react'
import { View, Text, ScrollView, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listShopGoodsCategory } from '@/api/shop/shopGoodsCategory'
import { pageShopGoods } from '@/api/shop/shopGoods'
import type { ShopGoodsCategory, ShopGoods } from '@/api/shop/shopGoodsCategory/model'
import type { ShopGoodsParam } from '@/api/shop/shopGoods/model'
import ProductCard from '@/components/common/ProductCard'
import EmptyState from '@/components/common/EmptyState'
import LoadMore from '@/components/common/LoadMore'

const categories = [
  { id: 0, title: '全部' },
  { id: -1, title: '推荐' },
]

const ShopPage: React.FC = () => {
  const [categoryList, setCategoryList] = useState<ShopGoodsCategory[]>(categories)
  const [activeCategory, setActiveCategory] = useState(0)
  const [goodsList, setGoodsList] = useState<ShopGoods[]>([])
  const [loading, setLoading] = useState(false)
  const [page, setPage] = useState(1)
  const [finished, setFinished] = useState(false)

  useEffect(() => {
    loadCategories()
  }, [])

  useEffect(() => {
    setPage(1)
    setFinished(false)
    setGoodsList([])
    loadGoods(1, activeCategory)
  }, [activeCategory])

  const loadCategories = async () => {
    try {
      const list = await listShopGoodsCategory()
      if (list && list.length > 0) {
        setCategoryList([...categories, ...list])
      }
    } catch { /* ignore */ }
  }

  const loadGoods = async (p: number, categoryId?: number) => {
    if (loading) return
    setLoading(true)
    try {
      const params: ShopGoodsParam = { page: p, limit: 10, status: 0 }
      if (categoryId && categoryId > 0) params.categoryId = categoryId
      if (categoryId === -1) params.recommend = 1
      const res = await pageShopGoods(params)
      const newList = res?.list || []
      if (p === 1) {
        setGoodsList(newList)
      } else {
        setGoodsList(prev => [...prev, ...newList])
      }
      setFinished(newList.length < 10)
      setPage(p)
    } catch { /* ignore */ }
    setLoading(false)
  }

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

  return (
    <View className='flex min-h-screen bg-gray-50'>
      {/* 左侧分类栏 */}
      <ScrollView scrollY className='w-20 bg-gray-100 h-screen'>
        {categoryList.map(cat => (
          <View
            key={cat.categoryId || cat.id}
            className={`py-3 px-2 text-center text-xs ${
              (cat.categoryId || cat.id) === activeCategory
                ? 'bg-white text-green-600 font-medium border-l-2 border-green-500'
                : 'text-gray-600'
            }`}
            onClick={() => setActiveCategory(cat.categoryId || cat.id)}
          >
            <Text>{cat.title}</Text>
          </View>
        ))}
      </ScrollView>

      {/* 右侧商品列表 */}
      <ScrollView
        scrollY
        className='flex-1 h-screen'
        onScrollToLower={handleLoadMore}
        lowerThreshold={100}
      >
        <View className='p-2'>
          <View className='grid grid-cols-2 gap-2'>
            {goodsList.map(item => (
              <ProductCard key={item.goodsId} product={item} />
            ))}
          </View>
          {goodsList.length === 0 && !loading && (
            <EmptyState text='暂无商品' />
          )}
          <LoadMore loading={loading} finished={finished} />
        </View>
      </ScrollView>
    </View>
  )
}

export default ShopPage
