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

export interface TabBarLayoutProps {
  children: ReactNode
  activeKey: string
}

const tabBarItems: TabBarItem[] = [
  {
    key: 'home',
    title: '首页',
    iconClass: 'i-heroicons-home-20-solid',
    selectedIconClass: 'i-heroicons-home-20-solid',
  },
  {
    key: 'category',
    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 }) => {
  const { cart } = useCart()
  const cartItemCount = cart.items.reduce((sum, item) => sum + item.quantity, 0)

  // 动态设置tabbar高度
  useEffect(() => {
    const setTabBarHeight = () => {
      try {
        // 计算tabbar高度（通常为100rpx）
        const tabbarHeightRpx = 100; // 标准tabbar高度

        // 设置CSS变量
        const rootElement = document.documentElement;
        if (rootElement) {
          rootElement.style.setProperty('--tabbar-height', `${tabbarHeightRpx}rpx`);
        }
      } catch (error) {
        console.error('设置tabbar高度失败:', error);
        // 使用默认值作为fallback
        const rootElement = document.documentElement;
        if (rootElement) {
          rootElement.style.setProperty('--tabbar-height', '100rpx');
        }
      }
    };

    setTabBarHeight();
  }, []);

  const handleTabChange = (key: string) => {
    // 使用 Taro 的导航 API 进行页面跳转
    switch (key) {
      case 'home':
        Taro.switchTab({ url: '/pages/index/index' })
        break
      case 'category':
        Taro.switchTab({ url: '/pages/category/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' && cartItemCount > 0) {
      return {
        ...item,
        badge: cartItemCount > 99 ? '99+' : cartItemCount
      }
    }
    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}
        selectedColor='#fa4126'
      />
    </View>
  )
}

export default TabBarLayout