import { View, ScrollView, Text, RichText, Input } from '@tarojs/components'
import { useQuery } from '@tanstack/react-query'
import { useState, useEffect } from 'react'
import Taro, { useRouter, useShareAppMessage } from '@tarojs/taro'
import { goodsClient } from '@/api'
// import { InferResponseType } from 'hono'
import { Navbar } from '@/components/ui/navbar'
import { Button } from '@/components/ui/button'
import { Carousel } from '@/components/ui/carousel'
import { GoodsSpecSelector } from '@/components/goods-spec-selector'
import { useCart } from '@/contexts/CartContext'
import './index.css'

// type GoodsResponse = InferResponseType<typeof goodsClient[':id']['$get'], 200>

interface SelectedSpec {
  id: number
  name: string
  price: number
  stock: number
}

interface Review {
  id: number
  userName: string
  rating: number
  content: string
  createTime: string
  images?: string[]
}

interface ReviewStats {
  averageRating: number
  totalCount: number
  goodRate: number
  ratingDistribution: {
    [key: number]: number
  }
}

export default function GoodsDetailPage() {
  const [quantity, setQuantity] = useState(1)
  const [selectedSpec, setSelectedSpec] = useState<SelectedSpec | null>(null)
  const [showSpecModal, setShowSpecModal] = useState(false)
  const [pendingAction, setPendingAction] = useState<'add-to-cart' | 'buy-now' | null>(null)
  const { addToCart } = useCart()

  // 模拟评价数据
  const [reviewStats] = useState<ReviewStats>({
    averageRating: 4.8,
    totalCount: 156,
    goodRate: 0.95,
    ratingDistribution: {
      5: 120,
      4: 25,
      3: 8,
      2: 2,
      1: 1
    }
  })

  const [reviews] = useState<Review[]>([
    {
      id: 1,
      userName: '用户****1234',
      rating: 5,
      content: '商品质量很好，物流很快，非常满意！包装也很精美，下次还会再来购买。',
      createTime: '2025-11-20'
    },
    {
      id: 2,
      userName: '用户****5678',
      rating: 4,
      content: '商品不错，性价比很高，就是物流稍微慢了一点，总体还是很满意的。',
      createTime: '2025-11-19'
    },
    {
      id: 3,
      userName: '用户****9012',
      rating: 5,
      content: '非常喜欢这个商品，质量超出预期，客服态度也很好，五星好评！',
      createTime: '2025-11-18'
    }
  ])

  // 使用useRouter钩子获取路由参数
  const router = useRouter()
  const params = router.params
  const goodsId = params?.id ? parseInt(params.id) : 0
  const fromPage = params?.from || ''

  const { data: goods, isLoading } = useQuery({
    queryKey: ['goods', goodsId],
    queryFn: async () => {
      const response = await goodsClient[':id'].$get({
        param: { id: goodsId }
      })
      if (response.status !== 200) {
        throw new Error('获取商品详情失败')
      }
      return response.json()
    },
    enabled: goodsId > 0,
    staleTime: 5 * 60 * 1000,
  })

  // 获取子商品列表，用于判断是否有规格选项
  const { data: childGoodsData } = useQuery({
    queryKey: ['goods', goodsId, 'children'],
    queryFn: async () => {
      const response = await goodsClient[':id'].children.$get({
        param: { id: goodsId },
        query: {
          page: 1,
          pageSize: 100, // 获取所有子商品，假设不会超过100个
          sortBy: 'createdAt',
          sortOrder: 'ASC'
        }
      })
      if (response.status !== 200) {
        throw new Error('获取子商品列表失败')
      }
      return response.json()
    },
    enabled: goodsId > 0,
    staleTime: 5 * 60 * 1000,
  })

  const hasSpecOptions = Boolean(childGoodsData && childGoodsData.data && childGoodsData.data.length > 0)


  // 商品轮播图
  const carouselItems = goods?.slideImages?.map((file: any) => ({
    src: file.fullUrl || '',
    title: goods.name,
    description: ''
  })) || []

  // 价格验证逻辑 - 简化版本，移除规格选择
  const validatePriceConsistency = () => {
    if (!goods) return

    const displayedPrice = goods.price
    const apiPrice = goods.price

    // 如果显示价格与API价格不一致，记录警告
    if (displayedPrice !== apiPrice) {
      // 在实际项目中可以发送错误报告或显示用户提示
    }
  }

  // 在商品数据变化时验证价格
  useEffect(() => {
    validatePriceConsistency()
  }, [goods])

  // 分享功能
  useShareAppMessage(() => {
    return {
      title: goods ? `${goods.name} - ¥${goods.price}` : '发现好物',
      path: `/pages/goods-detail/index?id=${goodsId}&from=share`,
      imageUrl: goods?.slideImages?.[0]?.fullUrl || goods?.imageFile?.fullUrl
    }
  })

  // 获取最大可购买数量
  const getMaxQuantity = () => {
    const targetStock = selectedSpec ? selectedSpec.stock : goods?.stock
    return Math.min(targetStock || 999, 999)
  }

  // 处理减少数量
  const handleDecrease = () => {
    const currentQty = quantity === 0 ? 1 : quantity
    const newQuantity = Math.max(1, currentQty - 1)
    setQuantity(newQuantity)
  }

  // 处理增加数量
  const handleIncrease = () => {
    const currentQty = quantity === 0 ? 1 : quantity
    const maxQuantity = getMaxQuantity()
    if (currentQty >= maxQuantity) {
      const targetStock = selectedSpec ? selectedSpec.stock : goods?.stock
      if (maxQuantity === targetStock) {
        Taro.showToast({
          title: `库存只有${targetStock}件`,
          icon: 'none',
          duration: 1500
        })
      } else {
        Taro.showToast({
          title: '单次最多购买999件',
          icon: 'none',
          duration: 1500
        })
      }
      return
    }
    setQuantity(currentQty + 1)
  }

  // 处理数量输入变化
  const handleQuantityChange = (value: string) => {
    // 清除非数字字符
    const cleanedValue = value.replace(/[^\d]/g, '')

    // 如果输入为空，设为空字符串（允许用户删除）
    if (cleanedValue === '') {
      setQuantity(0) // 设为0表示空输入
      return
    }

    const numValue = parseInt(cleanedValue)

    // 验证最小值
    if (numValue < 1) {
      setQuantity(1)
      Taro.showToast({
        title: '数量不能小于1',
        icon: 'none',
        duration: 1500
      })
      return
    }

    // 验证最大值
    const maxQuantity = getMaxQuantity()
    if (numValue > maxQuantity) {
      setQuantity(maxQuantity)
      const targetStock = selectedSpec ? selectedSpec.stock : goods?.stock
      if (maxQuantity === targetStock) {
        Taro.showToast({
          title: `库存只有${targetStock}件`,
          icon: 'none',
          duration: 1500
        })
      } else {
        Taro.showToast({
          title: '单次最多购买999件',
          icon: 'none',
          duration: 1500
        })
      }
      return
    }

    setQuantity(numValue)
  }

  // 处理输入框失去焦点（完成输入）
  const handleQuantityBlur = () => {
    // 如果数量小于1（表示空输入或负数），设为1
    if (quantity < 1) {
      setQuantity(1)
    }
  }

  // 规格选择确认
  const handleSpecConfirm = (spec: SelectedSpec | null, qty: number, actionType?: 'add-to-cart' | 'buy-now') => {
    if (spec) {
      setSelectedSpec(spec)
      setQuantity(qty)

      // 确定要执行的操作：优先使用传入的actionType，否则使用pendingAction状态
      const actionToExecute = actionType || pendingAction

      // 如果有待处理的操作，执行该操作
      if (actionToExecute && goods) {
        if (actionToExecute === 'add-to-cart') {
          // 执行添加到购物车操作
          const targetGoodsId = spec.id
          const targetGoodsName = spec.name
          const targetPrice = spec.price
          const targetStock = spec.stock
          const finalQuantity = qty === 0 ? 1 : qty

          if (finalQuantity > targetStock) {
            Taro.showToast({
              title: '库存不足',
              icon: 'none'
            })
            setPendingAction(null)
            setShowSpecModal(false)
            return
          }

          // 计算parentGoodsId：选择了规格，假设goods是父商品
          const parentGoodsId = goods.id

          addToCart({
            id: targetGoodsId,
            parentGoodsId: parentGoodsId,
            name: targetGoodsName,
            price: targetPrice,
            image: goods.imageFile?.fullUrl || '',
            stock: targetStock,
            quantity: finalQuantity
          })

          Taro.showToast({
            title: '已添加到购物车',
            icon: 'success'
          })
        } else if (actionToExecute === 'buy-now') {
          // 执行立即购买操作
          const targetGoodsId = spec.id
          const targetGoodsName = spec.name
          const targetPrice = spec.price
          const targetStock = spec.stock
          const finalQuantity = qty === 0 ? 1 : qty

          if (finalQuantity > targetStock) {
            Taro.showToast({
              title: '库存不足',
              icon: 'none'
            })
            setPendingAction(null)
            setShowSpecModal(false)
            return
          }

          Taro.removeStorageSync('buyNow')
          Taro.removeStorageSync('checkoutItems')

          // 将商品信息存入临时存储，跳转到订单确认页
          Taro.setStorageSync('buyNow', {
            goods: {
              id: targetGoodsId,
              name: targetGoodsName,
              price: targetPrice,
              image: goods.imageFile?.fullUrl || '',
              quantity: finalQuantity
            },
            totalAmount: targetPrice * finalQuantity
          })

          Taro.navigateTo({
            url: '/pages/order-submit/index'
          })
        }
      }
    }

    setPendingAction(null)
    setShowSpecModal(false)
  }

  // 打开规格选择弹窗
  const handleOpenSpecModal = () => {
    setShowSpecModal(true)
  }

  // 添加到购物车
  const handleAddToCart = () => {
    if (!goods) return

    // 如果是多规格商品，总是弹出规格选择器（无论是否已选择规格）
    if (hasSpecOptions) {
      setPendingAction('add-to-cart')
      setShowSpecModal(true)
      return
    }

    // 如果有选中的规格，使用规格信息；否则使用父商品信息
    const targetGoodsId = selectedSpec ? selectedSpec.id : goods.id
    const targetGoodsName = selectedSpec ? selectedSpec.name : goods.name
    const targetPrice = selectedSpec ? selectedSpec.price : goods.price
    const targetStock = selectedSpec ? selectedSpec.stock : goods.stock
    const targetSpec = selectedSpec ? selectedSpec.name : ''

    const finalQuantity = quantity === 0 ? 1 : quantity

    if (finalQuantity > targetStock) {
      Taro.showToast({
        title: '库存不足',
        icon: 'none'
      })
      return
    }

    // 计算parentGoodsId
    // 规则：
    // 1. 如果选择了规格（selectedSpec存在），parentGoodsId = goods.id（假设goods是父商品）
    // 2. 如果没有选择规格：
    //    - 如果goods.spuId === 0（商品是父商品），parentGoodsId = 0
    //    - 如果goods.spuId > 0（商品是子商品），parentGoodsId = goods.spuId
    let parentGoodsId = 0
    if (selectedSpec) {
      // 选择了规格，假设goods是父商品
      parentGoodsId = goods.id
    } else {
      // 没有选择规格
      if (goods.spuId === 0) {
        // 商品是父商品
        parentGoodsId = 0
      } else {
        // 商品是子商品，使用它的父商品ID
        parentGoodsId = goods.spuId
      }
    }

    addToCart({
      id: targetGoodsId,
      parentGoodsId: parentGoodsId,
      name: targetGoodsName,
      price: targetPrice,
      image: goods.imageFile?.fullUrl || '',
      stock: targetStock,
      quantity: finalQuantity
    })

    Taro.showToast({
      title: '已添加到购物车',
      icon: 'success'
    })
  }

  // 立即购买
  const handleBuyNow = () => {
    if (!goods) return

    // 如果是多规格商品，总是弹出规格选择器（无论是否已选择规格）
    if (hasSpecOptions) {
      setPendingAction('buy-now')
      setShowSpecModal(true)
      return
    }

    // 如果有选中的规格，使用规格信息；否则使用父商品信息
    const targetGoodsId = selectedSpec ? selectedSpec.id : goods.id
    const targetGoodsName = selectedSpec ? selectedSpec.name : goods.name
    const targetPrice = selectedSpec ? selectedSpec.price : goods.price
    const targetStock = selectedSpec ? selectedSpec.stock : goods.stock
    const targetSpec = selectedSpec ? selectedSpec.name : ''
    const finalQuantity = quantity === 0 ? 1 : quantity

    if (finalQuantity > targetStock) {
      Taro.showToast({
        title: '库存不足',
        icon: 'none'
      })
      return
    }

    Taro.removeStorageSync('buyNow')
    Taro.removeStorageSync('checkoutItems')

    // 将商品信息存入临时存储，跳转到订单确认页
    Taro.setStorageSync('buyNow', {
      goods: {
        id: targetGoodsId,
        name: targetGoodsName,
        price: targetPrice,
        image: goods.imageFile?.fullUrl || '',
        quantity: finalQuantity
      },
      totalAmount: targetPrice * finalQuantity
    })


    Taro.navigateTo({
      url: '/pages/order-submit/index'
    })
  }

  if (isLoading) {
    return (
      <View className="min-h-screen bg-gray-50 flex items-center justify-center">
        <View className="i-heroicons-arrow-path-20-solid animate-spin w-8 h-8 text-blue-500" />
      </View>
    )
  }

  if (!goods) {
    return (
      <View className="min-h-screen bg-gray-50 flex items-center justify-center">
        <Text className="text-gray-500">商品不存在</Text>
      </View>
    )
  }

  return (
    <View className="goods-detail-page">
      <Navbar
        title="商品详情"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => {
          // 根据来源页面决定返回逻辑
          //  分享，返回首页
          if (fromPage === 'share') {
             Taro.switchTab({
              url: `/pages/index/index`
            })
          } else {
           // 从其他页面来的，返回上一页
           Taro.navigateBack()
          }
        }}
      />

      <ScrollView className="goods-detail-scroll" scrollY>
        {/* 商品轮播图区域 */}
        <View className="goods-swiper-section">
          {carouselItems.length > 0 && (
            <Carousel
              items={carouselItems}
              height={750}
              autoplay={true}
              interval={4000}
              circular={true}
              onItemClick={(item, index) => {
                // 点击图片放大预览
                Taro.previewImage({
                  urls: carouselItems.map(item => item.src),
                  current: carouselItems[index].src
                })
              }}
            />
          )}
        </View>

        {/* 商品信息区域 */}
        <View className="goods-info-section">
          <View className="goods-price-row">
            <View className="price-container">
              <Text className="current-price">
                ¥{goods.price.toFixed(2)}
              </Text>
              <Text className="original-price">¥{goods.costPrice.toFixed(2)}</Text>
              {hasSpecOptions && <Text className="price-suffix">起</Text>}
            </View>
            <View className="sales-info">
              <Text className="sales-text">已售{goods.salesNum}件</Text>
            </View>
          </View>

          <Text className="goods-title">{goods.name}</Text>
          <Text className="goods-description">{goods.instructions || '暂无商品描述'}</Text>

        </View>

        {/* 商品评价区域 - 暂时移除，后端暂无评价API */}

        {/* 商品详情区域 */}
        <View className="detail-section">
          <Text className="detail-title">商品详情</Text>
          {goods.detail ? (
            <RichText
              className="detail-content"
              nodes={goods.detail
                .replace(/<img/g, '<img style="max-width:100%;height:auto;display:block;margin:0 auto"')
                .replace(/<p>/g, '<p style="margin:10px 0;line-height:1.6"')
                .replace(/<h1>/g, '<h1 style="font-size:32rpx;font-weight:bold;margin:20rpx 0"')
                .replace(/<h2>/g, '<h2 style="font-size:30rpx;font-weight:bold;margin:18rpx 0"')
                .replace(/<h3>/g, '<h3 style="font-size:28rpx;font-weight:bold;margin:16rpx 0"')
              }
            />
          ) : (
            <Text className="no-detail">暂无商品详情</Text>
          )}
        </View>
      </ScrollView>

      {/* 底部操作栏 */}
      <View className="bottom-action-bar">
        <View className="quantity-section">
          <Text className="quantity-label">数量</Text>
          <View className="quantity-controls">
            <Button
              size="sm"
              variant="ghost"
              className="quantity-btn"
              onClick={handleDecrease}
            >
              -
            </Button>
            <Input
              className="quantity-input"
              type="number"
              value={quantity === 0 ? '' : quantity.toString()}
              onInput={(e) => handleQuantityChange(e.detail.value)}
              onBlur={handleQuantityBlur}
              placeholder="1"
              maxlength={3}
              confirmType="done"
            />
            <Button
              size="sm"
              variant="ghost"
              className="quantity-btn"
              onClick={handleIncrease}
            >
              +
            </Button>
          </View>
        </View>



        <View className="button-section">
          <Button
            className="add-cart-btn"
            onClick={handleAddToCart}
            disabled={
              !goods
                ? true
                : hasSpecOptions
                  ? false // 多规格商品总是不禁用，总是允许用户点击按钮弹出规格选择器
                  : goods.stock <= 0
            }
          >
            加入购物车
          </Button>
          <Button
            className="buy-now-btn"
            onClick={handleBuyNow}
            disabled={
              !goods
                ? true
                : hasSpecOptions
                  ? false // 多规格商品总是不禁用，总是允许用户点击按钮弹出规格选择器
                  : goods.stock <= 0
            }
          >
            立即购买
          </Button>
        </View>
      </View>

      {/* 规格选择弹窗 */}
      <GoodsSpecSelector
        visible={showSpecModal}
        onClose={() => {
          setShowSpecModal(false)
          setPendingAction(null) // 重置待处理操作
        }}
        onConfirm={handleSpecConfirm}
        parentGoodsId={goods?.id || 0}
        currentSpec={selectedSpec?.name}
        currentQuantity={quantity}
        actionType={pendingAction}
      />
    </View>
  )
}