import React from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { TabBarLayout } from '@/layouts/tab-bar-layout'
import TDesignSearch from '@/components/tdesign/search'
import GoodsList from '@/components/goods-list'
import { GoodsData } from '@/components/goods-card'
import { goodsClient, advertisementClient } from '@/api'
import { InferResponseType } from 'hono'
import './index.css'
import { useAuth } from '@/utils/auth'
import { useCart } from '@/contexts/CartContext'
import { Navbar } from '@/components/ui/navbar'
import { Carousel } from '@/components/ui/carousel'
import Taro, { usePullDownRefresh, useShareAppMessage } from '@tarojs/taro'

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

const HomePage: React.FC = () => {
  const { isLoggedIn } = useAuth();
  const { addToCart } = useCart();
  const [refreshing, setRefreshing] = React.useState(false);
  
  // 广告数据查询
  const {
    data: advertisementData,
    isLoading: isAdLoading,
    error: adError
  } = useQuery({
    queryKey: ['home-advertisements'],
    queryFn: async () => {
      const response = await advertisementClient.$get({
        query: {
          filters: JSON.stringify({ status: 1, typeId: 1 }), // 过滤启用的首页轮播广告
          sortBy: 'sort', // 按sort字段排序
          sortOrder: 'ASC'
        }
      })
      if (response.status !== 200) {
        throw new Error('获取广告数据失败')
      }
      return response.json()
    },
    staleTime: 5 * 60 * 1000, // 5分钟缓存
  })

  const {
    data,
    isLoading,
    isFetchingNextPage,
    fetchNextPage,
    hasNextPage,
    error,
    refetch
  } = useInfiniteQuery({
    queryKey: ['home-goods-infinite'],
    queryFn: async ({ pageParam = 1 }) => {
      // console.debug('请求商品数据，页码:', pageParam)
      const response = await goodsClient.$get({
        query: {
          page: pageParam,
          pageSize: 10,
          filters: JSON.stringify({ state: 1 }), // 只显示可用的商品
          sortBy: 'sort', // 按sort字段排序
          sortOrder: 'DESC' // 倒序排列
        }
      })
      if (response.status !== 200) {
        throw new Error('获取商品失败')
      }
      const result = await response.json()
      // console.debug('API响应数据:', {
      //   page: pageParam,
      //   dataCount: result.data?.length || 0,
      //   pagination: result.pagination
      // })
      return result
    },
    getNextPageParam: (lastPage, _allPages) => {
      const { pagination } = lastPage
      const totalPages = Math.ceil(pagination.total / pagination.pageSize)

      // // 调试信息
      // console.debug('分页信息:', {
      //   current: pagination.current,
      //   pageSize: pagination.pageSize,
      //   total: pagination.total,
      //   totalPages,
      //   hasNext: pagination.current < totalPages,
      //   allPagesCount: allPages.length,
      //   allGoodsCount: allPages.flatMap(page => page.data).length
      // })

      return pagination.current < totalPages ? pagination.current + 1 : undefined
    },
    staleTime: 5 * 60 * 1000,
    initialPageParam: 1,
    enabled: isLoggedIn,
  })

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

  // 数据转换：将API返回的商品数据转换为GoodsData接口格式
  const convertToGoodsData = (goods: Goods): GoodsData => {
    // 判断是否有规格选项：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() || '', // 将number类型的id转换为string
      name: goods?.name || '',
      cover_image: imageUrl,
      price: goods?.price || 0,
      originPrice: (goods as any)?.originPrice || 0,
      tags: (goods?.salesNum || 0) > 100 ? ['热销'] : ['新品'],
      hasSpecOptions,
      parentGoodsId,
      stock: goods?.stock || 0,
      image: imageUrl, // 与cover_image保持一致
      quantity: 1 // 默认数量为1
    }
  }

  // 转换后的商品列表
  const goodsList = allGoods.map(convertToGoodsData)

  // 广告数据转换：提取图片URL并过滤掉没有图片的广告
  const finalImgSrcs = advertisementData?.data || []

  // 错误处理
  if (adError) {
    console.error('广告数据获取失败:', adError)
  }

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

  // 触底加载更多
  const handleScrollToLower = () => {
    // console.debug('触底加载更多:', {
    //   hasNextPage,
    //   isFetchingNextPage,
    //   allGoodsCount: allGoods.length,
    //   pagesCount: data?.pages?.length || 0,
    //   currentPage: data?.pages?.[data.pages.length - 1]?.pagination?.current || 0
    // })
    fetchNextPage();
    // if (hasNextPage && isFetchingNextPage) {
    //   console.debug('开始加载下一页...')
    //   fetchNextPage()
    // } else {
    //   console.debug('无法加载下一页，原因:', {
    //     hasNextPage,
    //     isFetchingNextPage
    //   })
    // }
  }

  // ScrollView下拉刷新处理函数
  const handleRefresh = () => {
    //console.log('首页下拉刷新触发 - ScrollView刷新处理函数被调用')
    //console.log('refetch函数:', refetch)
    //console.log('用户登录状态:', isLoggedIn)
    setRefreshing(true)
    refetch().finally(() => {
      //console.log('首页下拉刷新完成，停止刷新状态')
      setRefreshing(false)
      // 同时停止页面下拉刷新动画（如果同时启用）
      Taro.stopPullDownRefresh()
    })
  }

  // 暂时注释页面级下拉刷新钩子，使用ScrollView自带刷新
  // usePullDownRefresh(() => {
  //   console.log('首页下拉刷新触发 - 钩子被调用')
  //   console.log('refetch函数:', refetch)
  //   console.log('用户登录状态:', isLoggedIn)
  //   refetch().finally(() => {
  //     console.log('首页下拉刷新完成，停止刷新动画')
  //     Taro.stopPullDownRefresh()
  //   })
  // })

  // 分享功能
  useShareAppMessage(() => {
    return {
      title: '发现好物 - 精选商品推荐',
      path: '/pages/index/index',
      imageUrl: finalImgSrcs && finalImgSrcs.length > 0 ? finalImgSrcs[0].imageFile?.fullUrl : undefined
    }
  })

  // 如果未登录，不渲染页面内容
  if (!isLoggedIn) return null

  // 跳转到商品详情
  const handleGoodsClick = (goods: GoodsData, index: number) => {
    console.log('点击商品:', goods, index)
    // 安全解析商品ID：GoodsData.id是string类型，需要转换为number
    let goodsId: number
    if (typeof goods.id === 'number') {
      goodsId = goods.id
    } else if (typeof goods.id === 'string') {
      goodsId = parseInt(goods.id, 10)
    } else {
      console.error('商品ID类型无效:', goods.id, typeof goods.id)
      Taro.showToast({ title: '商品ID错误', icon: 'none' })
      return
    }
    if (isNaN(goodsId)) {
      console.error('商品ID解析失败:', goods.id)
      Taro.showToast({ title: '商品ID错误', icon: 'none' })
      return
    }
    Taro.navigateTo({
      url: `/pages/goods-detail/index?id=${goodsId}`
    })
  }

  // 添加购物车
  const handleAddCart = (goods: GoodsData, index: number) => {
    console.debug('[home] handleAddCart called', { goods, index, goodsId: goods.id, goodsIdType: typeof goods.id })
    // 直接使用传递的商品数据，不再依赖原始商品查找
    // 安全解析商品ID：支持数字和字符串类型
    let id: number
    if (typeof goods.id === 'number') {
      id = goods.id
    } else if (typeof goods.id === 'string') {
      id = parseInt(goods.id, 10)
    } else {
      console.error('商品ID类型无效:', goods.id, typeof goods.id)
      Taro.showToast({
        title: '商品ID错误',
        icon: 'none'
      })
      return
    }
    if (isNaN(id)) {
      console.error('商品ID解析失败:', goods.id)
      Taro.showToast({
        title: '商品ID错误',
        icon: 'none'
      })
      return
    }

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

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

  // 搜索框点击
  const handleSearchClick = () => {
    Taro.navigateTo({
      url: '/pages/search/index'
    })
  }

  return (
    <TabBarLayout activeKey="home">
      <Navbar
        title="首页"
        leftIcon=""
        onClickLeft={() => Taro.navigateBack()}
        rightIcon=""
        onClickRight={() => {}}
      />
      <ScrollView
        className="home-scroll-view"
        scrollY
        refresherEnabled={true}
        refresherTriggered={refreshing}
        onRefresherRefresh={handleRefresh}
        onScrollToLower={handleScrollToLower}      >
        {/* 页面头部 - 搜索栏和轮播图 */}
        <View className="home-page-header">
          {/* 搜索栏 */}
          <View className="search" onClick={handleSearchClick}>
            <TDesignSearch
              placeholder="搜索商品..."
              disabled={true}
              shape="round"
            />
          </View>

          {/* 轮播图 */}
          <View className="swiper-wrap">
            {isAdLoading ? (
              <View className="loading-container">
                <Text className="loading-text">广告加载中...</Text>
              </View>
            ) : adError ? (
              <View className="error-container">
                <Text className="error-text">广告加载失败</Text>
              </View>
            ) : finalImgSrcs && finalImgSrcs.length > 0 ? (
            
              <Carousel
                items={finalImgSrcs.filter(item => item.imageFile?.fullUrl).map(item => ({
                  src: item.imageFile!.fullUrl,
                  title: item.title || '',
                  description: (item as any).description || ''
                }))}
                height={800}
                autoplay={true}
                interval={4000}
                circular={true}
                imageMode="aspectFit"
              />
            
            )
            : (
              <View className="empty-container">
                <Text className="empty-text">暂无广告</Text>
              </View>
            )}
          </View>
        </View>

        {/* 页面内容 - 商品列表 */}
        <View className="home-page-container">
          {isLoading ? (
            <View className="loading-container">
              <Text className="loading-text">加载中...</Text>
            </View>
          ) : error ? (
            <View className="error-container">
              <Text className="error-text">加载失败，请重试</Text>
            </View>
          ) : goodsList.length === 0 ? (
            <View className="empty-container">
              <Text className="empty-text">暂无商品</Text>
            </View>
          ) : (
            <>
              <GoodsList
                goodsList={goodsList}
                onClick={handleGoodsClick}
                onAddCart={handleAddCart}
              />

              {/* 加载更多状态 */}
              {isFetchingNextPage && (
                <View className="loading-more-container">
                  <Text className="loading-more-text">加载更多...</Text>
                </View>
              )}

              {/* 无更多数据状态 */}
              {!hasNextPage && goodsList.length > 0 && (
                <View className="no-more-container">
                <Text className="no-more-text">
                  {`已经到底啦 (共${goodsList.length}件商品)`}
                </Text>
              </View>
              )}
            </>
          )}
          <View className='height130'></View>
        </View>
        
      </ScrollView>
    </TabBarLayout>
  )
}

export default HomePage
