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

definePageConfig({
  navigationBarTitleText: '商品分类',
})

const CategoryPage: React.FC = () => {
  const [categories, setCategories] = useState<ShopGoodsCategory[]>([])
  const [activeId, setActiveId] = useState<number | undefined>()

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

  const loadCategories = async () => {
    try {
      const list = await listShopGoodsCategory()
      if (list) {
        // 过滤：只保留 status=1 且有子分类的分类，避免空壳分类导致审核被拒
        const filtered = list
          .map(cat => ({
            ...cat,
            children: (cat.children || []).filter(child => child.status === 1),
          }))
          .filter(cat => cat.status === 1 && cat.children.length > 0)
        setCategories(filtered)
        if (filtered.length > 0) setActiveId(filtered[0].categoryId)
      }
    } catch { /* ignore */ }
  }

  const activeCategory = categories.find(c => c.categoryId === activeId)
  const children = activeCategory?.children || []

  return (
    <View className='flex min-h-screen bg-gray-50'>
      {/* 左侧一级分类 */}
      <ScrollView scrollY className='w-24 bg-gray-100 h-screen'>
        {categories.map(cat => (
          <View
            key={cat.categoryId}
            className={`py-3 px-3 text-center text-sm ${
              cat.categoryId === activeId
                ? 'bg-white text-green-600 font-medium border-l-2 border-green-500'
                : 'text-gray-600'
            }`}
            onClick={() => setActiveId(cat.categoryId)}
          >
            <Text>{cat.title}</Text>
          </View>
        ))}
      </ScrollView>

      {/* 右侧二级分类 */}
      <ScrollView scrollY className='flex-1 h-screen'>
        {children.length > 0 ? (
          <View className='p-3'>
            <View className='grid grid-cols-3 gap-3'>
              {children.map(child => (
                <View
                  key={child.categoryId}
                  className='flex flex-col items-center py-2'
                  onClick={() => Taro.switchTab({ url: '/pages/shop/index' })}
                >
                  <View className='w-14 h-14 rounded-lg bg-gray-100 overflow-hidden mb-1'>
                    {child.image ? (
                      <Image className='w-full h-full' src={child.image} mode='aspectFill' />
                    ) : (
                      <View className='w-full h-full flex items-center justify-center'>
                        <Text className='text-xs text-gray-300'>{(child.title || '')[0]}</Text>
                      </View>
                    )}
                  </View>
                  <Text className='text-xs text-gray-600 text-center'>{child.title}</Text>
                </View>
              ))}
            </View>
          </View>
        ) : (
          <EmptyState text='暂无分类' />
        )}
      </ScrollView>
    </View>
  )
}

export default CategoryPage
