import { Text, View } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { EmptyState, Page, ProductImage } from '@/components/ui'
import { ensureLoggedIn, getCart, removeCartItem } from '@/stores/storage'
import type { CartItem } from '@/types'
import { tapHeavy, tapLight } from '@/utils/feedback'

export default function CartPage() {
  const [items, setItems] = useState<CartItem[]>([])
  useDidShow(() => {
    const user = ensureLoggedIn('/pages/cart/index')
    if (!user) return
    setItems(getCart())
  })

  function remove(id: string) {
    tapHeavy()
    setItems(removeCartItem(id))
  }

  const total = items.reduce((sum, item) => sum + item.price, 0)

  return (
    <Page title="购物车" subtle={items.length ? `共 ${items.length} 项服务` : undefined}>
      {items.length === 0 ? (
        <EmptyState title="购物车还是空的" text="先去浏览课程、活动、数据服务或智能体服务。" action={<View className="ghost-btn" onClick={() => Taro.switchTab({ url: '/pages/services/index' })}>去看服务</View>} />
      ) : (
        <View className="commerce-page">
          <View className="commerce-list">
            {items.map((item) => (
              <View key={item.id} className="commerce-row">
                <ProductImage className="commerce-thumb" src={item.cover} />
                <View className="commerce-main">
                  <Text className="commerce-title">{item.title}</Text>
                  <Text className="commerce-sub">{item.subtitle}</Text>
                  <Text className="commerce-price">¥{item.price.toLocaleString()}</Text>
                </View>
                <Text className="cart-remove" onClick={() => remove(item.id)}>移除</Text>
              </View>
            ))}
          </View>
          <View className="detail-spacer" />
          <View className="checkout-fixed-bar">
            <View className="checkout-total-copy">
              <Text className="checkout-total-label">合计</Text>
              <Text className="checkout-total-price">¥{total.toLocaleString()}</Text>
            </View>
            <View className="primary-btn checkout-submit" onClick={() => { tapLight(); Taro.navigateTo({ url: '/pages/checkout/index' }) }}>去结算</View>
          </View>
        </View>
      )}
    </Page>
  )
}
