import { View, ScrollView, Text } from '@tarojs/components'
import { useInfiniteQuery } from '@tanstack/react-query'
import { useState } from 'react'
import Taro, { usePullDownRefresh , useReachBottom, useRouter,useShareAppMessage, useShareTimeline} from '@tarojs/taro'
import { goodsClient } from '@/api'
import { InferResponseType } from 'hono'
import { Navbar } from '@/components/ui/navbar'
import { useCart } from '@/contexts/CartContext'
import GoodsList from '@/components/goods-list'
import TDesignSearch from '@/components/tdesign/search'
import type { GoodsData } from '@/components/goods-card'

type GoodsResponse = InferResponseType<typeof goodsClient.$get, 200>
type Goods = GoodsResponse['data'][0]

export default function GoodsListPage() {
  const [searchKeyword, setSearchKeyword] = useState('')
  const [activeCategory, setActiveCategory] = useState('all')
  const { addToCart } = useCart()

  // 使用useRouter钩子获取路由参数
  const router = useRouter()
  const params = router.params
  const categoryId = params?.cateId || ''
  const fromPage = params?.from || ''

  const categories = [
    { id: 'all', name: '全部' },
    { id: 'hot', name: '热销' },
    { id: 'new', name: '新品' },
  ]


  const {
    data,
    isLoading,
    isFetchingNextPage,
    fetchNextPage,
    hasNextPage,
    refetch
  } = useInfiniteQuery({
    queryKey: ['goods-infinite', searchKeyword, categoryId],
    queryFn: async ({ pageParam = 1 }) => {
      // 构建筛选条件
      const filters: any = { state: 1 } // 只显示可用的商品
      if (categoryId) {
        filters.categoryId1 = categoryId
      }

      const response = await goodsClient.$get({
        query: {
          page: pageParam,
          pageSize: 10,
          keyword: searchKeyword,
          filters: JSON.stringify(filters),
          sortBy: 'sort', // 按sort字段排序
          sortOrder: 'DESC' // 倒序排列
        }
      })
      if (response.status !== 200) {
        throw new Error('获取商品失败')
      }
      return response.json()
    },
    getNextPageParam: (lastPage) => {
      const { pagination } = lastPage
      const totalPages = Math.ceil(pagination.total / pagination.pageSize)
      return pagination.current < totalPages ? pagination.current + 1 : undefined
    },
    staleTime: 5 * 60 * 1000,
    initialPageParam: 1,
  })

  // 合并所有分页数据
  const allGoods = data?.pages.flatMap(page => page.data) || []

  // 分享功能 - 分享给好友
  useShareAppMessage(() => {
    // 如果有商品数据，使用第一个商品的图片作为分享图片
    const shareImageUrl = allGoods.length > 0 ? allGoods[0]?.imageFile?.fullUrl || '' : '';

    // 构建分享标题
    let shareTitle = '商品分类 - 发现好物';
    if (searchKeyword) {
      shareTitle = `搜索"${searchKeyword}" - 发现好物`;
    } else if (categoryId) {
      shareTitle = `商品分类 - 发现好物`;
    }

    return {
      title: shareTitle,
      path: `/pages/goods-list/index?cateId=${encodeURIComponent(categoryId)}&keyword=${encodeURIComponent(searchKeyword)}&from=share`,
      imageUrl: shareImageUrl
    }
  })

  // 分享到朋友圈功能
  useShareTimeline(() => {
    // 朋友圈分享需要图片，使用第一个商品的图片
    const shareImageUrl = allGoods.length > 0 ? allGoods[0]?.imageFile?.fullUrl || '' : '';

    // 朋友圈分享标题
    let shareTitle = '发现好物，快来选购！';
    if (searchKeyword) {
      shareTitle = `搜索"${searchKeyword}"发现的好物`;
    } else if (categoryId) {
      shareTitle = `精选商品，等你来选`;
    }

    return {
      title: shareTitle,
      imageUrl: shareImageUrl,
      query: `cateId=${encodeURIComponent(categoryId)}&keyword=${encodeURIComponent(searchKeyword)}&from=timeline`
    }
  })

  // 使用Taro全局钩子 - 触底加载更多
  useReachBottom(() => {
    if (hasNextPage && !isFetchingNextPage) {
      fetchNextPage()
    }
  })

  // 使用Taro全局钩子 - 下拉刷新
  usePullDownRefresh(() => {
    refetch().finally(() => {
      Taro.stopPullDownRefresh()
    })
  })

  // 跳转到商品详情
  const handleGoodsClick = (goods: Goods) => {
    Taro.navigateTo({
      url: `/pages/goods-detail/index?id=${goods.id}`
    })
  }

  // 添加到购物车
  const handleAddToCart = (goodsData: GoodsData) => {
    // 直接使用传递的商品数据，不再依赖原始商品查找
    const id = parseInt(goodsData.id)
    if (isNaN(id)) {
      console.error('商品ID解析失败:', goodsData.id)
      Taro.showToast({
        title: '商品ID错误',
        icon: 'none'
      })
      return
    }

    // 验证必要字段
    if (!goodsData.name) {
      console.warn('商品名称为空，使用默认值')
    }

    addToCart({
      id: id,
      parentGoodsId: goodsData.parentGoodsId || 0, // 默认为0（单规格商品）
      name: goodsData.name || '未命名商品',
      price: goodsData.price || 0,
      image: goodsData.image || goodsData.cover_image || '', // 优先使用image字段，其次cover_image
      stock: goodsData.stock || 0,
      quantity: goodsData.quantity || 1
    })
    Taro.showToast({
      title: '已添加到购物车',
      icon: 'success'
    })
  }

  return (
    <View className="min-h-screen bg-white">
      <Navbar
        title="商品列表"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => {
                          // 根据来源页面决定返回逻辑
                          //  分享，返回首页
                          if (fromPage === 'share') {
                             Taro.switchTab({
                              url: `/pages/index/index`
                            })
                          } else {
                           // 从其他页面来的
                           Taro.navigateBack()
                          }
                        }}
        className="bg-white shadow-sm"
      />
      
      <ScrollView
        className="flex-1"
        scrollY
      >
        <View className="goods-page-container bg-[#f2f2f2] p-[20rpx_24rpx]">
          {/* 搜索栏 */}
          <View className="search-bar-container mb-4">
            <View onClick={() => Taro.navigateTo({ url: '/pages/search/index' })}>
              <TDesignSearch
                placeholder="搜索你想要的商品..."
                shape="round"
                value={searchKeyword}
                onChange={(value) => setSearchKeyword(value)}
                onSubmit={() => refetch()}
                onClear={() => {
                  setSearchKeyword('')
                  refetch()
                }}
                disabled={true}
              />
            </View>
          </View>

          {/* 分类筛选 */}
          {/* <View className="flex space-x-2 mb-4 overflow-x-auto">
            {categories.map((category) => (
              <View
                key={category.id}
                className={`whitespace-nowrap rounded-full px-4 py-2 transition-all cursor-pointer ${
                  activeCategory === category.id
                    ? 'bg-blue-500 text-white shadow-md'
                    : 'text-gray-600 bg-gray-100 hover:bg-gray-200'
                }`}
                onClick={() => {
                  setActiveCategory(category.id)
                  refetch()
                }}
              >
                {category.name}
              </View>
            ))}
          </View> */}

          {/* 商品列表 */}
          {isLoading ? (
            <View className="flex justify-center py-10">
              <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
            </View>
          ) : (
            <>
              <GoodsList
                goodsList={allGoods.map(goods => {
                  // 判断是否有规格选项：spuId === 0 表示是父商品，且有子商品列表
                  // 根据GoodsServiceMt实现，父商品返回childGoodsIds字段
                  const childGoodsIds = (goods as any).childGoodsIds
                  const hasSpecOptions = goods.spuId === 0 && childGoodsIds && childGoodsIds.length > 0
                  // parentGoodsId: 如果是父商品，parentGoodsId = goods.id；如果是子商品，parentGoodsId = goods.spuId
                  const parentGoodsId = goods.spuId === 0 ? goods.id : goods.spuId
                  const imageUrl = goods.imageFile?.fullUrl || ''

                  return {
                    id: goods.id.toString(),
                    name: goods.name,
                    cover_image: imageUrl,
                    price: goods.price,
                    originPrice: goods.originPrice,
                    tags: goods.stock <= 0 ? ['已售罄'] : goods.salesNum > 100 ? ['热销'] : [],
                    hasSpecOptions,
                    parentGoodsId,
                    stock: goods.stock || 0,
                    image: imageUrl, // 与cover_image保持一致
                    quantity: 1 // 默认数量为1
                  }
                })}
                onClick={(goods) => handleGoodsClick(allGoods.find(g => g.id.toString() === goods.id)!)}
                onAddCart={(goods) => handleAddToCart(goods)}
              />
              
              {isFetchingNextPage && (
                <View className="flex justify-center py-4 mt-4">
                  <View className="i-heroicons-arrow-path-20-solid animate-spin w-6 h-6 text-blue-500" />
                  <Text className="ml-2 text-sm text-gray-500">加载更多...</Text>
                </View>
              )}
              
              {!hasNextPage && allGoods.length > 0 && (
                <View className="text-center py-8 text-sm text-gray-400">
                  <View className="flex items-center justify-center">
                    <View className="i-heroicons-check-circle-20-solid w-4 h-4 mr-1" />
                    已经到底啦
                  </View>
                </View>
              )}
              
              {!isLoading && allGoods.length === 0 && (
                <View className="flex flex-col items-center py-10">
                  <View className="i-heroicons-inbox-20-solid w-16 h-16 text-gray-300 mb-4" />
                  <Text className="text-gray-500 text-lg mb-2">暂无商品</Text>
                  <Text className="text-gray-400 text-sm">换个关键词试试吧</Text>
                </View>
              )}
            </>
          )}
        </View>
      </ScrollView>
    </View>
  )
}