import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'

export interface CartItem {
  id: number
  name: string
  price: number
  image: string
  stock: number
  quantity: number
}

export interface CartState {
  items: CartItem[]
  totalAmount: number
  totalCount: number
}

const CART_STORAGE_KEY = 'mini_cart'

export const useCart = () => {
  const [cart, setCart] = useState<CartState>({
    items: [],
    totalAmount: 0,
    totalCount: 0
  })
  const [isLoading, setIsLoading] = useState(true)

  // 从本地存储加载购物车
  useEffect(() => {
    const loadCart = () => {
      try {
        const savedCart = Taro.getStorageSync(CART_STORAGE_KEY)
        if (savedCart && Array.isArray(savedCart.items)) {
          const totalAmount = savedCart.items.reduce((sum: number, item: CartItem) =>
            sum + (item.price * item.quantity), 0)
          const totalCount = savedCart.items.reduce((sum: number, item: CartItem) =>
            sum + item.quantity, 0)
          
          setCart({
            items: savedCart.items,
            totalAmount,
            totalCount
          })
        }
      } catch (error) {
        console.error('加载购物车失败:', error)
      } finally {
        setIsLoading(false)
      }
    }

    loadCart()
  }, [])

  // 保存购物车到本地存储
  const saveCart = (items: CartItem[]) => {
    const totalAmount = items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    const totalCount = items.reduce((sum, item) => sum + item.quantity, 0)
    
    const newCart = {
      items,
      totalAmount,
      totalCount
    }
    
    setCart(newCart)
    
    try {
      Taro.setStorageSync(CART_STORAGE_KEY, { items })
    } catch (error) {
      console.error('保存购物车失败:', error)
    }
  }

  // 添加商品到购物车
  const addToCart = (item: CartItem) => {
    const existingItem = cart.items.find(cartItem => cartItem.id === item.id)
    
    if (existingItem) {
      // 如果商品已存在，增加数量
      const newQuantity = Math.min(existingItem.quantity + item.quantity, item.stock)
      if (newQuantity === existingItem.quantity) {
        Taro.showToast({
          title: '库存不足',
          icon: 'none'
        })
        return
      }
      
      const newItems = cart.items.map(cartItem =>
        cartItem.id === item.id
          ? { ...cartItem, quantity: newQuantity }
          : cartItem
      )
      saveCart(newItems)
      Taro.showToast({
        title: '已更新购物车',
        icon: 'success'
      })
    } else {
      // 添加新商品
      if (item.quantity > item.stock) {
        Taro.showToast({
          title: '库存不足',
          icon: 'none'
        })
        return
      }
      
      saveCart([...cart.items, item])
    }
  }

  // 从购物车移除商品
  const removeFromCart = (id: number) => {
    const newItems = cart.items.filter(item => item.id !== id)
    saveCart(newItems)
    Taro.showToast({
      title: '已移除商品',
      icon: 'success'
    })
  }

  // 更新商品数量
  const updateQuantity = (id: number, quantity: number) => {
    const item = cart.items.find(item => item.id === id)
    if (!item) return
    
    if (quantity <= 0) {
      removeFromCart(id)
      return
    }
    
    if (quantity > item.stock) {
      Taro.showToast({
        title: '库存不足',
        icon: 'none'
      })
      return
    }
    
    const newItems = cart.items.map(item =>
      item.id === id ? { ...item, quantity } : item
    )
    saveCart(newItems)
  }

  // 清空购物车
  const clearCart = () => {
    saveCart([])
    Taro.showToast({
      title: '已清空购物车',
      icon: 'success'
    })
  }

  // 检查商品是否在购物车中
  const isInCart = (id: number) => {
    return cart.items.some(item => item.id === id)
  }

  // 获取购物车中商品数量
  const getItemQuantity = (id: number) => {
    const item = cart.items.find(item => item.id === id)
    return item ? item.quantity : 0
  }

  return {
    cart,
    addToCart,
    removeFromCart,
    updateQuantity,
    clearCart,
    isInCart,
    getItemQuantity,
    isLoading
  }
}