import { View, Text, Image, ScrollView, Button } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState, useMemo } from 'react'
import { getCart, updateQuantity, removeItem, toggleSelect, toggleSelectAll, CartItem } from '../../utils/cart'
import './cart.scss'

export default function Cart() {
  const [cartItems, setCartItems] = useState<CartItem[]>([])

  useDidShow(() => {
    refreshCart()
  })

  const refreshCart = () => {
    setCartItems(getCart())
  }

  const handleUpdateQuantity = (id: number, delta: number) => {
    const item = cartItems.find(i => i.id === id)
    if (!item) return
    const newQty = item.quantity + delta
    if (newQty < 1) return
    const newCart = updateQuantity(id, newQty)
    setCartItems(newCart)
  }

  const handleRemove = (id: number) => {
    Taro.showModal({
      title: '提示',
      content: '确定要删除该商品吗？',
      success: (res) => {
        if (res.confirm) {
          const newCart = removeItem(id)
          setCartItems(newCart)
        }
      }
    })
  }

  const handleToggle = (id: number) => {
    const newCart = toggleSelect(id)
    setCartItems(newCart)
  }

  const isAllSelected = useMemo(() => {
    return cartItems.length > 0 && cartItems.every(i => i.selected)
  }, [cartItems])

  const handleToggleAll = () => {
    const newCart = toggleSelectAll(!isAllSelected)
    setCartItems(newCart)
  }

  const selectedCount = useMemo(() => {
    return cartItems.filter(i => i.selected).reduce((sum, i) => sum + i.quantity, 0)
  }, [cartItems])

  const totalPrice = useMemo(() => {
    return cartItems.filter(i => i.selected).reduce((sum, i) => sum + i.price * i.quantity, 0)
  }, [cartItems])

  const handleCheckout = () => {
    if (selectedCount === 0) {
      Taro.showToast({ title: '请选择商品', icon: 'none' })
      return
    }
    Taro.navigateTo({
      url: '/pages/order/checkout?from=cart'
    })
  }

  const goShopping = () => {
    Taro.switchTab({ url: '/pages/index/index' })
  }

  return (
    <View className='page-container'>
      {cartItems.length === 0 ? (
        <View className='empty-state'>
          <Text className='empty-icon'>🛒</Text>
          <Text className='empty-text'>购物车空空如也</Text>
          <Button onClick={goShopping} style={{marginTop: 20, background: '#00b96b', color: '#fff'}}>去逛逛</Button>
        </View>
      ) : (
        <ScrollView scrollY className='cart-list'>
          {cartItems.map(item => (
            <View key={item.id} className='cart-item'>
              <View className='checkbox-area' onClick={() => handleToggle(item.id)}>
                <View className={`checkbox ${item.selected ? 'checked' : ''}`}>
                  {item.selected && <Text>✓</Text>}
                </View>
              </View>
              
              <Image src={item.image} className='item-img' mode='aspectFill' />
              
              <View className='item-info'>
                <View>
                  <Text className='item-name'>{item.name}</Text>
                  {/* <Text className='item-desc'>{item.description}</Text> */}
                </View>
                
                <View className='price-row'>
                  <Text className='price'>¥{item.price}</Text>
                  
                  <View className='quantity-control'>
                    <View className='btn-qty' onClick={() => handleUpdateQuantity(item.id, -1)}>−</View>
                    <Text className='qty-num'>{item.quantity}</Text>
                    <View className='btn-qty' onClick={() => handleUpdateQuantity(item.id, 1)}>+</View>
                  </View>
                </View>
              </View>
              
              <View className='btn-delete' onClick={() => handleRemove(item.id)}>×</View>
            </View>
          ))}
        </ScrollView>
      )}

      {cartItems.length > 0 && (
        <View className='bottom-bar'>
          <View className='left-section'>
            <View className='select-all-btn' onClick={handleToggleAll}>
              <View className={`checkbox ${isAllSelected ? 'checked' : ''}`}>
                {isAllSelected && <Text>✓</Text>}
              </View>
              <Text className='label'>全选</Text>
            </View>
            
            <View className='total-info'>
              <Text className='label'>合计:</Text>
              <Text className='price'>¥{totalPrice}</Text>
            </View>
          </View>
          
          <Button 
            className={`btn-checkout ${selectedCount === 0 ? 'disabled' : ''}`} 
            onClick={handleCheckout}
          >
            去结算({selectedCount})
          </Button>
        </View>
      )}
    </View>
  )
}
