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

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

const SearchResultPage: React.FC = () => {
  const { addToCart } = useCart()

  // 使用useRouter钩子获取路由参数
  const router = useRouter()
  const params = router.params
  const searchKeyword = params?.keyword || ''

  // 直接使用路由参数，无需useEffect
  const [keyword, setKeyword] = useState(decodeURIComponent(searchKeyword))
  const [searchValue, setSearchValue] = useState(decodeURIComponent(searchKeyword))

  const {
    data,
    isLoading,
    isFetchingNextPage,
    fetchNextPage,
    hasNextPage,
    refetch
  } = useInfiniteQuery({
    queryKey: ['search-goods-infinite', keyword],
    queryFn: async ({ pageParam = 1 }) => {
      const response = await goodsClient.$get({
        query: {
          page: pageParam,
          pageSize: 10,
          keyword: keyword,
          filters: JSON.stringify({ state: 1 }) // 只显示可用的商品
        }
      })
      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,
    enabled: !!keyword, // 只有有搜索关键词时才执行查询
  })

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

  // 触底加载更多
  const handleScrollToLower = () => {
    if (hasNextPage && !isFetchingNextPage) {
      fetchNextPage()
    }
  }

  // 下拉刷新
  const onPullDownRefresh = () => {
    refetch().finally(() => {
      Taro.stopPullDownRefresh()
    })
  }

  // 处理输入变化
  const handleInputChange = (e: any) => {
    const value = e.detail.value
    setSearchValue(value)

    // 实时搜索，无防抖
    if (!value.trim()) {
      // 空搜索，清空keyword
      setKeyword('')
      return
    }

    // 更新搜索关键词并重新搜索
    setKeyword(value)
    refetch()
  }

  // 处理搜索提交（用于按钮和回车）
  const handleSubmit = (value: string) => {
    if (!value.trim()) return

    // 执行搜索
    setKeyword(value)
    setSearchValue(value)
    refetch()
  }

  // 跳转到商品详情
  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="search-result-page">
      <Navbar
        title="搜索结果"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
        className="bg-white"
      />

      <ScrollView
        className="search-result-content"
        scrollY
        onScrollToLower={handleScrollToLower}
        refresherEnabled
        refresherTriggered={false}
        onRefresherRefresh={onPullDownRefresh}
      >
        {/* 搜索栏 - 参照tcb-shop-demo设计 */}
        <View className="search-bar-container">
          <View className="search-input-wrapper">
            <View className="i-heroicons-magnifying-glass-20-solid search-icon" />
            <Input
              className="search-input"
              placeholder="搜索商品..."
              value={searchValue}
              onInput={handleInputChange}
              onConfirm={() => handleSubmit(searchValue)}
            />
            {searchValue && (
              <View
                className="i-heroicons-x-mark-20-solid clear-icon"
                onClick={() => {
                  setSearchValue('')
                  setKeyword('') // 清空keyword，重置搜索状态
                }}
              />
            )}
          </View>
        </View>

        {/* 搜索结果 */}
        <View className="result-container">
          {/* 搜索结果标题 */}
          {keyword && (
            <View className="result-header">
              <Text className="result-title">
                搜索结果："{keyword}"
              </Text>
              <Text className="result-count">
                共找到 {data?.pages[0]?.pagination?.total || 0} 件商品
              </Text>
            </View>
          )}

          {/* 商品列表 */}
          {isLoading ? (
            <View className="loading-container">
              <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
              <Text className="loading-text">搜索中...</Text>
            </View>
          ) : allGoods.length === 0 ? (
            <View className="empty-container">
              <View className="i-heroicons-magnifying-glass-20-solid empty-icon" />
              <Text className="empty-text">
                {keyword ? '暂无相关商品' : '请输入搜索关键词'}
              </Text>
              <Text className="empty-subtext">
                {keyword ? '换个关键词试试吧' : '搜索你想要的商品'}
              </Text>
            </View>
          ) : (
            <>
              <View className="goods-list-container">
                <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保持一致
                    }
                  })}
                  onClick={(goods) => handleGoodsClick(allGoods.find(g => g.id.toString() === goods.id)!)}
                  onAddCart={(goods) => handleAddToCart(goods)}
                />
              </View>

              {/* 加载更多状态 */}
              {isFetchingNextPage && (
                <View className="loading-more-container">
                  <View className="i-heroicons-arrow-path-20-solid animate-spin w-6 h-6 text-blue-500" />
                  <Text className="loading-more-text">加载更多...</Text>
                </View>
              )}

              {/* 无更多数据状态 */}
              {!hasNextPage && allGoods.length > 0 && (
                <View className="no-more-container">
                  <View className="i-heroicons-check-circle-20-solid w-4 h-4 mr-1" />
                  <Text className="no-more-text">已经到底啦</Text>
                </View>
              )}
            </>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default SearchResultPage