import { View, ScrollView, Text, Image, RichText } from '@tarojs/components'
import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import Taro from '@tarojs/taro'
import { goodsClient } from '@/api'
import { InferResponseType } from 'hono'
import { Navbar } from '@/components/ui/navbar'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Carousel } from '@/components/ui/carousel'
import { useCart } from '@/utils/cart'

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

export default function GoodsDetailPage() {
  const [quantity, setQuantity] = useState(1)
  const { addToCart } = useCart()
  
  // 获取商品ID
  const params = Taro.getCurrentInstance().router?.params
  const goodsId = params?.id ? parseInt(params.id) : 0

  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 carouselItems = goods?.slideImages?.map(file => ({
    src: file.fullUrl || '',
    title: goods.name,
    description: ''
  })) || []

  // 添加到购物车
  const handleAddToCart = () => {
    if (!goods) return
    
    if (quantity > goods.stock) {
      Taro.showToast({
        title: '库存不足',
        icon: 'none'
      })
      return
    }

    addToCart({
      id: goods.id,
      name: goods.name,
      price: goods.price,
      image: goods.imageFile?.fullUrl || '',
      stock: goods.stock,
      quantity
    })
    
    Taro.showToast({
      title: '已添加到购物车',
      icon: 'success'
    })
  }

  // 立即购买
  const handleBuyNow = () => {
    if (!goods) return
    
    if (quantity > goods.stock) {
      Taro.showToast({
        title: '库存不足',
        icon: 'none'
      })
      return
    }

    // 将商品信息存入临时存储，跳转到订单确认页
    Taro.setStorageSync('buyNow', {
      goods: {
        id: goods.id,
        name: goods.name,
        price: goods.price,
        image: goods.imageFile?.fullUrl || '',
        quantity
      },
      totalAmount: goods.price * quantity
    })
    
    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="min-h-screen bg-gray-50">
      <Navbar
        title="商品详情"
        leftIcon="i-heroicons-chevron-left-20-solid"
        onClickLeft={() => Taro.navigateBack()}
      />
      
      <ScrollView className="h-screen pt-12 pb-20">
        {/* 商品轮播图 */}
        {carouselItems.length > 0 && (
          <View className="mb-4">
            <Carousel
              items={carouselItems}
              height={375}
              autoplay={true}
              interval={4000}
              circular={true}
            />
          </View>
        )}

        <View className="px-4 space-y-4">
          {/* 商品信息 */}
          <Card>
            <View className="p-4">
              <Text className="text-xl font-bold text-gray-900 mb-2">
                {goods.name}
              </Text>
              
              <Text className="text-sm text-gray-500 mb-4">
                {goods.instructions || '暂无商品描述'}
              </Text>
              
              <View className="flex items-center justify-between mb-4">
                <View>
                  <Text className="text-red-500 text-2xl font-bold">
                    ¥{goods.price.toFixed(2)}
                  </Text>
                  <Text className="text-sm text-gray-400 line-through ml-2">
                    ¥{goods.costPrice.toFixed(2)}
                  </Text>
                </View>
                <View className="text-sm text-gray-500">
                  库存: {goods.stock}件
                </View>
              </View>
              
              <View className="text-sm text-gray-500">
                已售: {goods.salesNum}件
              </View>
            </View>
          </Card>

          {/* 商品详情 */}
          <Card>
            <View className="p-4">
              <Text className="text-lg font-bold mb-4">商品详情</Text>
              {goods.detail ? (
                <RichText
                  nodes={goods.detail
                    .replace(/<img/g, '<img style="max-width:100%;height:auto"')
                    .replace(/<p>/g, '<p style="margin:10px 0">')
                  }
                />
              ) : (
                <Text className="text-gray-500">暂无商品详情</Text>
              )}
            </View>
          </Card>
        </View>
      </ScrollView>

      {/* 底部操作栏 */}
      <View className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 py-3">
        <View className="flex items-center justify-between">
          <View className="flex items-center">
            <Text className="text-gray-600 mr-2">数量:</Text>
            <View className="flex items-center border border-gray-300 rounded">
              <Button
                size="sm"
                variant="ghost"
                className="px-3"
                onClick={() => setQuantity(Math.max(1, quantity - 1))}
              >
                -
              </Button>
              <Text className="px-4 py-1 border-x border-gray-300">{quantity}</Text>
              <Button
                size="sm"
                variant="ghost"
                className="px-3"
                onClick={() => setQuantity(Math.min(goods.stock, quantity + 1))}
              >
                +
              </Button>
            </View>
          </View>
          
          <View className="flex space-x-2">
            <Button 
              variant="outline"
              onClick={handleAddToCart}
              disabled={goods.stock <= 0}
            >
              加入购物车
            </Button>
            <Button 
              onClick={handleBuyNow}
              disabled={goods.stock <= 0}
            >
              立即购买
            </Button>
          </View>
        </View>
      </View>
    </View>
  )
}