import Taro from '@tarojs/taro'
import { useShareAppMessage } from "@tarojs/taro"
import { useEffect, useState, useRef, useCallback } from "react"
import { View, Text, ScrollView } from '@tarojs/components'
import { Image } from '@nutui/nutui-react-taro'
import {listCmsNavigation} from "@/api/cms/cmsNavigation"
import { CmsNavigation } from "@/api/cms/cmsNavigation/model"
import { pageShopGoods } from "@/api/shop/shopGoods"
import { ShopGoods } from "@/api/shop/shopGoods/model"
import './category.scss'

function Category() {
  const [loading, setLoading] = useState<boolean>(true)
  const [categories, setCategories] = useState<CmsNavigation[]>([])
  const [selectedCategoryId, setSelectedCategoryId] = useState<number>(0)
  const [goods, setGoods] = useState<{ [key: number]: ShopGoods[] }>({})
  const [allGoods, setAllGoods] = useState<ShopGoods[]>([])
  const rightScrollRef = useRef<any>(null)
  const [scrollIntoView, setScrollIntoView] = useState('')
  const [isScrollingByClick, setIsScrollingByClick] = useState(false)

  // 初始化数据
  const initData = async () => {
    try {
      setLoading(true)
      const home = await listCmsNavigation({home: 1})
      // 获取商品分类
      const categoryList = await listCmsNavigation({ parentId: home[0].navigationId || 0, position: 1 })

      if (!categoryList || categoryList.length === 0) {
        Taro.showToast({
          title: '暂无商品分类',
          icon: 'none'
        })
        setLoading(false)
        return
      }

      setCategories(categoryList)
      const firstCategory = categoryList[0]
      setSelectedCategoryId(firstCategory.navigationId!)

      // 并行获取所有分类的商品数据
      const goodsPromises = categoryList.map((category: CmsNavigation) =>
        pageShopGoods({ categoryId: category.navigationId }).catch(err => {
          console.error(`分类 ${category.title} 商品加载失败:`, err)
          return { list: [] }
        })
      )

      const goodsResults = await Promise.all(goodsPromises)

      // 组织商品数据
      const goodsByCategory: { [key: number]: ShopGoods[] } = {}
      categoryList.forEach((category: CmsNavigation, index: number) => {
        goodsByCategory[category.navigationId!] = goodsResults[index]?.list || []
      })

      setGoods(goodsByCategory)

      // 获取所有商品用于搜索等功能
      try {
        const allGoodsRes = await pageShopGoods({})
        setAllGoods(allGoodsRes?.list || [])
      } catch (err) {
        console.error('获取所有商品失败:', err)
      }

      Taro.setNavigationBarTitle({
        title: '商品分类'
      })
    } catch (error) {
      console.error('分类数据加载失败:', error)
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    initData().then()
    console.log(allGoods,'allGoods')
  }, [])

  // 点击左侧分类
  const handleCategoryClick = (categoryId: number) => {
    setIsScrollingByClick(true)
    setSelectedCategoryId(categoryId)
    setScrollIntoView(`category-${categoryId}`)

    // 延迟重置滚动标志
    setTimeout(() => {
      setIsScrollingByClick(false)
    }, 1000)
  }

  // 右侧滚动时处理分类切换
  const handleRightScroll = useCallback((e: any) => {
    console.log(e,'右侧滚动时处理分类切换')
    if (isScrollingByClick) return

    // 这里可以添加逻辑来检测当前滚动到哪个分类
    // 由于小程序限制，暂时简化处理
  }, [isScrollingByClick])

  // 跳转商品详情
  const goToGoodsDetail = (goodsId: number) => {
    Taro.navigateTo({ url: `/shop/goodsDetail/index?id=${goodsId}` })
  }

  useShareAppMessage(() => {
    return {
      title: '商品分类',
      path: '/pages/category/category',
      success: function () {
        console.log('分享成功')
      },
      fail: function () {
        console.log('分享失败')
      }
    }
  })

  // 骨架屏组件
  const CategorySkeleton = () => (
    <View className="category-skeleton" style={{
      marginTop: '1rpx',
    }}>
      <View className="category-left">
        {[1, 2, 3, 4, 5].map(i => (
          <View key={i} className="skeleton-category-item">
            <View className="skeleton-text" />
          </View>
        ))}
      </View>
      <View className="category-right">
        {[1, 2, 3, 4].map(i => (
          <View key={i} className="skeleton-goods-item">
            <View className="skeleton-image" />
            <View className="skeleton-info">
              <View className="skeleton-text" style={{ width: '80%', marginBottom: '8px' }} />
              <View className="skeleton-text" style={{ width: '60%' }} />
            </View>
          </View>
        ))}
      </View>
    </View>
  )

  if (loading) {
    return <CategorySkeleton />
  }

  // 空状态处理
  if (!categories || categories.length === 0) {
    return (
      <View className="empty-container">
        <View className="empty-content">
          <Text className="empty-icon">📋</Text>
          <Text className="empty-title">暂无商品分类</Text>
          <Text className="empty-desc">请稍后再试或联系客服</Text>
          <View className="empty-action" onClick={initData}>
            <Text>重新加载</Text>
          </View>
        </View>
      </View>
    )
  }

  return (
    <View className="category-container" style={{
      marginTop: '1rpx',
    }}>
      {/* 左侧分类导航 */}
      <View className="category-left">
        <ScrollView
          className="category-scroll"
          scrollY
          enhanced
          showScrollbar={false}
        >          {categories.map((category) => (
            <View
              key={category.navigationId}
              className={`category-item ${
                selectedCategoryId === category.navigationId ? 'active' : ''
              }`}
              onClick={() => handleCategoryClick(category.navigationId!)}
            >
              <Text className="category-name">{category.title}</Text>
            </View>
          ))}
        </ScrollView>
      </View>

      {/* 右侧商品列表 */}
      <View className="category-right">
        <ScrollView
          ref={rightScrollRef}
          className="goods-scroll"
          scrollY
          enhanced
          showScrollbar={false}
          scrollIntoView={scrollIntoView}
          onScroll={handleRightScroll}
        >
          {categories.map((category) => {
            const categoryGoods = goods[category.navigationId!] || []
            return (
              <View
                key={category.navigationId}
                id={`category-${category.navigationId}`}
                className="goods-section"
              >
                <View className="section-title">
                  <Text>{category.title}</Text>
                </View>

                {categoryGoods.length > 0 ? (
                  <View className="goods-list">
                    {categoryGoods.map((item) => (
                      <View
                        key={item.goodsId}
                        className="goods-item"
                        onClick={() => goToGoodsDetail(item.goodsId!)}
                      >
                        <Image
                          className="goods-image"
                          src={item.image || ''}
                          mode="aspectFill"
                          lazyLoad
                          width={80}
                          height={80}
                        />
                        <View className="goods-info">
                          <Text className="goods-name">{item.name}</Text>
                          {item.comments && (
                            <Text className="goods-desc">{item.comments}</Text>
                          )}
                          <View className="goods-price-row">
                            <Text className="goods-price">¥{item.price}</Text>
                            {item.salePrice && Number(item.salePrice) !== Number(item.price) && (
                              <Text className="goods-original-price">¥{item.salePrice}</Text>
                            )}
                          </View>
                          {item.stock !== undefined && (
                            <Text className="goods-stock">
                              库存: {item.stock > 0 ? item.stock : '缺货'}
                            </Text>
                          )}
                        </View>
                      </View>
                    ))}
                  </View>
                ) : (
                  <View className="empty-section">
                    <Text>该分类暂无商品</Text>
                  </View>
                )}
              </View>
            )
          })}
        </ScrollView>
      </View>
    </View>
  )
}

export default Category
