import React, { useEffect } from "react";
import { Tabs } from "expo-router";
import { useTabConfig } from "@/constants/config";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { initSocket } from "@/services/socket";
import { useSnackbar } from "@/contexts/Snackbar";
import NetInfo from "@react-native-community/netinfo";

export default function TabLayout() {
  const { isLoggedIn } = useSelector((state: RootState) => state.auth);
  if (!isLoggedIn) return null;
  const TAB_CONFIG = useTabConfig();

  const { showSnackbar } = useSnackbar();
  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      const isConnected = state.isConnected;

      if (isConnected === false) {
        console.log("No internet connection");
        showSnackbar("No internet connection", "error");
      }
    });

    return () => {
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    initSocket();
  }, [isLoggedIn]);
  return (
    <Tabs
      screenOptions={{
        tabBarStyle: {
          backgroundColor: "#252A34",
          borderTopLeftRadius: 12,
          borderTopRightRadius: 12,
          position: "absolute",
          overflow: "hidden",
        },
        tabBarActiveTintColor: "#fff",
        tabBarInactiveTintColor: "#aaa",
      }}
    >
      {TAB_CONFIG.map(({ name, title, Icon, IconFilled }) => (
        <Tabs.Screen
          key={name}
          name={name}
          options={{
            title,
            tabBarIcon: ({ color, focused }) => {
              const IconComponent = focused ? IconFilled : Icon;
              return <IconComponent />;
            },
          }}
        />
      ))}
    </Tabs>
  );
}
