import { Tabs } from 'expo-router';
import React from 'react';
import { TabBarIcon } from '@/components/navigation/TabBarIcon';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { HapticTab } from '@/components/HapticTab';
import { TransitionPresets } from '@react-navigation/bottom-tabs';
import { Platform } from 'react-native';
import AskNavbar from '@/components/layout/ask';
import { webSocketManager, WebSocketStatus } from '@/lib/websocket-util';
import { useEffect, useState } from 'react';

// 只在iOS平台上导入TabBarBackground组件
const TabBarBackground = Platform.OS === 'ios' ? require('@/components/ui/TabBarBackground').default : null;

export default function TabLayout() {
  const colorScheme = useColorScheme();
  const [wsStatus, setWsStatus] = useState<WebSocketStatus>('disconnected');

  useEffect(() => {
    const handleStatusChange = (status: WebSocketStatus) => {
      setWsStatus(status);
    };
    webSocketManager.subscribeStatus(handleStatusChange);
    return () => {
      webSocketManager.unsubscribeStatus(handleStatusChange);
    };
  }, []);

  // 只在iOS平台上使用TabBarBackground
  const renderTabBarBackground = () => {
    if (Platform.OS === 'ios' && TabBarBackground) {
      return <TabBarBackground />;
    }
    return null;
  };

  return (
    <>
      <Tabs
        screenOptions={{
          tabBarActiveTintColor: Colors[colorScheme ?? 'light'].tint,
          headerShown: false,
          tabBarBackground: renderTabBarBackground, // 使用自定义背景
          tabBarButton: HapticTab, // 添加触觉反馈
        }}
      >
        <Tabs.Screen
          name="index"
          options={{
            title: 'Home',
            tabBarIcon: ({ color }) => <TabBarIcon name="home" color={color} />,
            ...TransitionPresets.ShiftTransition,
          }}
        />
        <Tabs.Screen
          name="memo-list"
          options={{
            title: 'Memos',
            tabBarIcon: ({ color }) => <TabBarIcon name="document-text" color={color} />,
            ...TransitionPresets.ShiftTransition,
          }}
        />
        <Tabs.Screen
          name="owner"
          options={{
            title: 'Profile',
            tabBarIcon: ({ color }) => <TabBarIcon name="person" color={color} />,
            ...TransitionPresets.ShiftTransition,
          }}
        />
      </Tabs>
      <AskNavbar wsStatus={wsStatus} />
    </>
  );
}
