import { View, ScrollView, Text, Input } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { useQueries } from '@tanstack/react-query'
import Taro from '@tarojs/taro'
import { Navbar } from '@/components/ui/navbar'
import { Button } from '@/components/ui/button'
import { Image } from '@/components/ui/image'
import { useCart } from '@/contexts/CartContext'
import { TabBarLayout } from '@/layouts/tab-bar-layout'
import { goodsClient } from '@/api'
import clsx from 'clsx'
import './index.css'

export default function CartPage() {
  const { cart, updateQuantity, removeFromCart, clearCart, isLoading } = useCart()
  const [selectedItems, setSelectedItems] = useState<number[]>([])
  const [showSkeleton, setShowSkeleton] = useState(true)
  // 为每个商品维护本地输入值，用于显示空字符串
  const [inputValues, setInputValues] = useState<{[key: number]: string}>({})

  // 为每个购物车商品创建查询，从数据库重新获取最新信息
  const goodsQueries = useQueries({
    queries: cart.items.map(item => ({
      queryKey: ['cart-goods', item.id],
      queryFn: async () => {
        const response = await goodsClient[':id'].$get({
          param: { id: item.id }
        })
        if (response.status !== 200) {
          throw new Error('获取商品详情失败')
        }
        return response.json()
      },
      enabled: item.id > 0,
      staleTime: 5 * 60 * 1000, // 5分钟缓存
    }))
  })

  // 创建商品ID到最新商品信息的映射
  const goodsMap = new Map()
  goodsQueries.forEach((query, index) => {
    if (query.data && cart.items[index]) {
      goodsMap.set(cart.items[index].id, query.data)
    }
  })

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedItems.length === cart.items.length) {
      setSelectedItems([])
    } else {
      setSelectedItems(cart.items.map(item => item.id))
    }
  }

  // 选择/取消选择商品
  const toggleSelectItem = (id: number) => {
    setSelectedItems(prev =>
      prev.includes(id)
        ? prev.filter(itemId => itemId !== id)
        : [...prev, id]
    )
  }

  // 计算选中商品的总价，使用从数据库获取的最新价格
  const selectedItemsTotal = cart.items
    .filter(item => selectedItems.includes(item.id))
    .reduce((sum, item) => {
      const latestGoods = goodsMap.get(item.id)
      const price = latestGoods?.price || item.price // 优先使用数据库价格，没有则使用本地价格
      return sum + (price * item.quantity)
    }, 0)

  // 添加骨架屏效果
  useEffect(() => {
    if (!isLoading) {
      const timer = setTimeout(() => setShowSkeleton(false), 300)
      return () => clearTimeout(timer)
    }
  }, [isLoading])

  // 去结算
  const handleCheckout = () => {
    if (selectedItems.length === 0) {
      Taro.showToast({
        title: '请选择商品',
        icon: 'none'
      })
      return
    }

    const checkoutItems = cart.items.filter(item => selectedItems.includes(item.id))

    Taro.removeStorageSync('buyNow')
    Taro.removeStorageSync('checkoutItems')
    
    // 存储选中的商品信息
    Taro.setStorageSync('checkoutItems', {
      items: checkoutItems,
      totalAmount: selectedItemsTotal
    })

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


  // 骨架屏组件
  const CartSkeleton = () => (
    <View className="cart-skeleton">
      {[...Array(3)].map((_, index) => (
        <View key={index} className="cart-group">
          <View className="goods-item">
            <View className="goods-item-info">
              <View className="check-wrap">
                <View className="check-icon skeleton" />
              </View>
              <View className="goods-sku-info">
                <View className="goods-card horizontal-wrap">
                  <View className="goods-thumb skeleton" />
                  <View className="goods-body">
                    <View className="goods-title skeleton" />
                    <View className="goods-specs skeleton" />
                    <View className="goods-price skeleton" />
                    <View className="cart-quantity-controls skeleton" />
                  </View>
                </View>
              </View>
            </View>
          </View>
        </View>
      ))}
    </View>
  )

  return (
    <TabBarLayout
      activeKey="cart"
    >
      <Navbar
        title="购物车"
        leftIcon=""
        onClickLeft={() => Taro.navigateBack()}
        rightIcon="i-heroicons-trash-20-solid"
        onClickRight={() => {
          Taro.showModal({
            title: '清空购物车',
            content: '确定要清空购物车吗？',
            success: (res) => {
              if (res.confirm) {
                clearCart()
                setSelectedItems([])
              }
            }
          })
        }}
      />

      <ScrollView
        className="cart-container"
        scrollY
        scrollWithAnimation
      >
        {showSkeleton && cart.items.length === 0 ? (
          <CartSkeleton />
        ) : cart.items.length === 0 ? (
          <View className="cart-empty">
            <View className="cart-empty-image" />
            <Text className="cart-empty-tip">购物车是空的</Text>
            <Button
              onClick={() => Taro.navigateTo({ url: '/pages/goods-list/index' })}
              className="cart-empty-btn"
            >
              去首页逛逛
            </Button>
          </View>
        ) : (
          <View className="cart-content">
            {/* 商品列表 */}
            <View className="cart-group" >
              {cart.items.map((item) => {
                // 获取从数据库重新获取的最新商品信息
                const latestGoods = goodsMap.get(item.id)
                // 优先使用数据库中的最新信息，如果没有则使用本地保存的信息
                const goodsName = latestGoods?.name || item.name
                const goodsPrice = latestGoods?.price || item.price
                const goodsImage = latestGoods?.imageFile?.fullUrl || item.image
                const goodsStock = latestGoods?.stock || item.stock

                return (
                <View key={item.id} className="goods-item">
                  <View className="goods-item-info">
                    {/* 选择框 */}
                    <View
                      className="check-wrap"
                      onClick={() => toggleSelectItem(item.id)}
                    >
                      <View
                        className={clsx(
                          'check-icon',
                          selectedItems.includes(item.id) ? 'selected' : ''
                        )}
                      >
                        {selectedItems.includes(item.id) && (
                          <View className="i-heroicons-check-20-solid w-3 h-3 text-white" />
                        )}
                      </View>
                    </View>

                    {/* 商品卡片 */}
                    <View className="goods-sku-info">
                      <View
                        className="goods-card horizontal-wrap"
                        onClick={() => Taro.navigateTo({
                          url: `/pages/goods-detail/index?id=${item.id}&from=cart`
                        })}
                      >
                        {/* 商品图片 */}
                        <View className="goods-thumb">
                          <Image
                            src={goodsImage && goodsImage.trim() !== '' ? goodsImage : 'https://via.placeholder.com/150x150?text=商品图片'}
                            className="thumb-image"
                            mode="aspectFill"
                            // retryCount={2} // 重试2次
                            // retryDelay={1500} // 每次重试间隔1.5秒
                            onError={() => {
                              console.warn('商品图片加载失败:', item.id, goodsName, goodsImage)
                            }}
                            onLoad={() => {
                              console.log('商品图片加载成功:', item.id, goodsName)
                            }}
                            errorPlaceholder={
                              <View className="absolute inset-0 flex items-center justify-center bg-gray-100">
                                <View className="text-center">
                                  <View className="i-heroicons-photo-20-solid w-8 h-8 text-gray-400 mx-auto mb-2" />
                                  <Text className="text-xs text-gray-500">图片加载失败</Text>
                                </View>
                              </View>
                            }
                          />
                          {goodsStock <= 3 && (
                            <View className="stock-mask">
                              仅剩{goodsStock}件
                            </View>
                          )}
                        </View>

                        {/* 商品信息 */}
                        <View className="goods-body">
                          <Text className="goods-title">{goodsName}</Text>

                          {item.spec && (
                            <View className="goods-specs">
                              <Text className="specs-text">{item.spec}</Text>
                              <View className="i-heroicons-chevron-down-20-solid w-4 h-4 text-gray-400" />
                            </View>
                          )}

                          <View className="goods-price-section">
                            <Text className="goods-price">¥{goodsPrice.toFixed(2)}</Text>
                          </View>

                          {/* 数量选择器 */}
                          <View
                            className="cart-quantity-controls"
                            onClick={(e) => {
                              e.stopPropagation(); // 阻止事件冒泡到商品卡片
                            }}
                            onTouchStart={(e) => {
                              e.stopPropagation(); // 阻止触摸事件冒泡
                            }}
                          >
                            <Button
                              size="sm"
                              variant="ghost"
                              className="cart-quantity-btn"
                              onClick={(e) => {
                                e.stopPropagation(); // 阻止事件冒泡
                                // 清除本地输入值
                                setInputValues(prev => {
                                  const newValues = { ...prev };
                                  delete newValues[item.id];
                                  return newValues;
                                });
                                updateQuantity(item.id, Math.max(1, item.quantity - 1));
                              }}
                              onTouchStart={(e) => {
                                e.stopPropagation(); // 阻止触摸开始事件冒泡
                              }}
                              onTouchEnd={(e) => {
                                e.stopPropagation(); // 阻止触摸结束事件冒泡
                              }}
                              disabled={item.quantity <= 1}
                            >
                              -
                            </Button>
                            <Input
                              className="cart-quantity-input"
                              type="number"
                              value={inputValues[item.id] !== undefined ? inputValues[item.id] : item.quantity.toString()}
                              onClick={(e) => {
                                e.stopPropagation(); // 阻止点击事件冒泡
                              }}
                              onTouchStart={(e) => {
                                e.stopPropagation(); // 阻止触摸开始事件冒泡
                              }}
                              onTouchEnd={(e) => {
                                e.stopPropagation(); // 阻止触摸结束事件冒泡
                              }}
                              onInput={(e) => {
                                e.stopPropagation(); // 阻止事件冒泡
                                const value = e.detail.value;
                                // 清除非数字字符
                                const cleanedValue = value.replace(/[^\d]/g, '');

                                // 更新本地输入值
                                setInputValues(prev => ({
                                  ...prev,
                                  [item.id]: value // 使用原始值，允许显示空字符串
                                }));

                                // 如果输入为空，只更新本地状态，不更新购物车
                                if (cleanedValue === '') {
                                  return;
                                }

                                const numValue = parseInt(cleanedValue);

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

                                // 验证最大值（考虑库存和单次购买限制）
                                const maxQuantity = Math.min(goodsStock, 999);
                                if (numValue > maxQuantity) {
                                  updateQuantity(item.id, maxQuantity);
                                  if (maxQuantity === goodsStock) {
                                    Taro.showToast({
                                      title: `库存只有${goodsStock}件`,
                                      icon: 'none',
                                      duration: 1500
                                    });
                                  } else {
                                    Taro.showToast({
                                      title: '单次最多购买999件',
                                      icon: 'none',
                                      duration: 1500
                                    });
                                  }
                                  return;
                                }

                                updateQuantity(item.id, numValue);
                              }}
                              onBlur={(e) => {
                                e.stopPropagation(); // 阻止事件冒泡
                                const value = e.detail.value;
                                const cleanedValue = value.replace(/[^\d]/g, '');

                                // 清除本地输入值，恢复显示购物车数量
                                setInputValues(prev => {
                                  const newValues = { ...prev };
                                  delete newValues[item.id];
                                  return newValues;
                                });

                                // 如果输入为空，不更新数量
                                if (cleanedValue === '') {
                                  return;
                                }

                                const numValue = parseInt(cleanedValue);

                                // 如果输入无效（小于1），设为1
                                if (numValue < 1) {
                                  updateQuantity(item.id, 1);
                                  Taro.showToast({
                                    title: '数量不能小于1',
                                    icon: 'none',
                                    duration: 1500
                                  });
                                }
                              }}
                              onFocus={(e) => {
                                e.stopPropagation(); // 阻止焦点事件冒泡
                              }}
                              onConfirm={(e) => {
                                e.stopPropagation(); // 阻止事件冒泡
                                const value = e.detail.value;
                                const cleanedValue = value.replace(/[^\d]/g, '');

                                // 清除本地输入值
                                setInputValues(prev => {
                                  const newValues = { ...prev };
                                  delete newValues[item.id];
                                  return newValues;
                                });

                                // 如果输入为空，设为1
                                if (cleanedValue === '') {
                                  updateQuantity(item.id, 1);
                                  return;
                                }

                                const numValue = parseInt(cleanedValue);

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

                                // 验证最大值（考虑库存和单次购买限制）
                                const maxQuantity = Math.min(goodsStock, 999);
                                if (numValue > maxQuantity) {
                                  updateQuantity(item.id, maxQuantity);
                                  if (maxQuantity === goodsStock) {
                                    Taro.showToast({
                                      title: `库存只有${goodsStock}件`,
                                      icon: 'none',
                                      duration: 1500
                                    });
                                  } else {
                                    Taro.showToast({
                                      title: '单次最多购买999件',
                                      icon: 'none',
                                      duration: 1500
                                    });
                                  }
                                  return;
                                }

                                updateQuantity(item.id, numValue);
                              }}
                              placeholder="1"
                              maxlength={3}
                              confirmType="done"
                            />
                            <Button
                              size="sm"
                              variant="ghost"
                              className="cart-quantity-btn"
                              onClick={(e) => {
                                e.stopPropagation(); // 阻止事件冒泡
                                // 清除本地输入值
                                setInputValues(prev => {
                                  const newValues = { ...prev };
                                  delete newValues[item.id];
                                  return newValues;
                                });
                                // 验证最大值（考虑库存和单次购买限制）
                                const maxQuantity = Math.min(goodsStock, 999);
                                if (item.quantity >= maxQuantity) {
                                  if (maxQuantity === goodsStock) {
                                    Taro.showToast({
                                      title: `库存只有${goodsStock}件`,
                                      icon: 'none',
                                      duration: 1500
                                    });
                                  } else {
                                    Taro.showToast({
                                      title: '单次最多购买999件',
                                      icon: 'none',
                                      duration: 1500
                                    });
                                  }
                                  return;
                                }
                                updateQuantity(item.id, item.quantity + 1);
                              }}
                              onTouchStart={(e) => {
                                e.stopPropagation(); // 阻止触摸开始事件冒泡
                              }}
                              onTouchEnd={(e) => {
                                e.stopPropagation(); // 阻止触摸结束事件冒泡
                              }}
                              disabled={item.quantity >= Math.min(goodsStock, 999)}
                            >
                              +
                            </Button>
                          </View>


                        </View>
                      </View>
                    </View>
                  </View>

                  {/* 删除按钮 */}
                  <View
                    className="delete-btn"
                    onClick={() => {
                      Taro.showModal({
                        title: '删除商品',
                        content: '确定要删除这个商品吗？',
                        success: (res) => {
                          if (res.confirm) {
                            removeFromCart(item.id)
                            setSelectedItems(prev => prev.filter(id => id !== item.id))
                          }
                        }
                      })
                    }}
                  >
                    删除
                  </View>
                </View>
                )
              })}
            </View>


            {/* 底部留白 */}
            <View className="cart-bottom-gap" />
          </View>
        )}
      </ScrollView>

      {/* 底部结算栏 */}
      {cart.items.length > 0 && (
        <View className="cart-bar">
          <View
            className="cart-bar-check"
            onClick={toggleSelectAll}
          >
            <View
              className={clsx(
                'check-icon',
                selectedItems.length === cart.items.length ? 'selected' : ''
              )}
            >
              {selectedItems.length === cart.items.length && (
                <View className="i-heroicons-check-20-solid w-3 h-3 text-white" />
              )}
            </View>
            <Text className="cart-bar-text">全选</Text>
          </View>

          <View className="cart-bar-total">
            <View>
              <Text className="total-label">总计</Text>
              <Text className="total-amount">¥{selectedItemsTotal.toFixed(2)}</Text>
            </View>
          </View>

          <Button
            onClick={handleCheckout}
            disabled={selectedItems.length === 0}
            className={clsx(
              'settle-btn',
              selectedItems.length > 0 ? 'active' : 'disabled'
            )}
          >
            去结算({selectedItems.length})
          </Button>
        </View>
      )}
    </TabBarLayout>
  )
}