import React, { ReactNode } from 'react'
import { View } from '@tarojs/components'
import { TabBar, TabBarItem } from '@/components/ui/tab-bar'
import Taro from '@tarojs/taro'

export interface TabBarLayoutProps {
  children: ReactNode
  activeKey: string
  cartCount?: number
}

const tabBarItems: TabBarItem[] = [
  {
    key: 'home',
    title: '首页',
    iconClass: 'i-heroicons-home-20-solid',
    selectedIconClass: 'i-heroicons-home-20-solid',
  },
  {
    key: 'goods-list',
    title: '商品',
    iconClass: 'i-heroicons-squares-2x2-20-solid',
    selectedIconClass: 'i-heroicons-squares-2x2-20-solid',
  },
  {
    key: 'cart',
    title: '购物车',
    iconClass: 'i-heroicons-shopping-cart-20-solid',
    selectedIconClass: 'i-heroicons-shopping-cart-20-solid',
  },
  {
    key: 'profile',
    title: '我的',
    iconClass: 'i-heroicons-user-20-solid',
    selectedIconClass: 'i-heroicons-user-20-solid',
  },
]

export const TabBarLayout: React.FC<TabBarLayoutProps> = ({ children, activeKey, cartCount }) => {
  const handleTabChange = (key: string) => {
    // 使用 Taro 的导航 API 进行页面跳转
    switch (key) {
      case 'home':
        Taro.switchTab({ url: '/pages/index/index' })
        break
      case 'goods-list':
        Taro.switchTab({ url: '/pages/goods-list/index' })
        break
      case 'cart':
        Taro.switchTab({ url: '/pages/cart/index' })
        break
      case 'profile':
        Taro.switchTab({ url: '/pages/profile/index' })
        break
      default:
        break
    }
  }

  // 动态设置购物车标签的角标
  const tabItemsWithBadge = tabBarItems.map(item => {
    if (item.key === 'cart' && cartCount && cartCount > 0) {
      return {
        ...item,
        badge: cartCount > 99 ? '99+' : cartCount
      }
    }
    return item
  })

  return (
    <View className="min-h-screen bg-gray-50 flex flex-col">
      <View className="flex-1 flex flex-col">
        {children}
      </View>
      <TabBar
        items={tabItemsWithBadge}
        activeKey={activeKey}
        onChange={handleTabChange}
        fixed={true}
        safeArea={true}
      />
    </View>
  )
}

export default TabBarLayout