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

export default function TabLayout() {
  const { isLoggedIn } = useSelector((state: RootState) => state.auth);
  if (!isLoggedIn) return null;
  const TAB_CONFIG = useTabConfig();
  const dispatch = useDispatch<AppDispatch>();
  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(() => {
    const fetchAndInit = async () => {
      try {
        const result = await dispatch(getUserDetails()).unwrap();
        await dispatch(getPaymentSummary());
        console.log("User details fetched", result);
        initSocket();
      } catch (error) {
        console.error("Failed to fetch user details", error);
        showSnackbar("Failed to fetch user details", "error");
      }
    };

    if (isLoggedIn) {
      fetchAndInit();
    }
  }, [isLoggedIn]);
  return (
    <Tabs
      screenOptions={{
        headerShadowVisible: false,
        tabBarStyle: {
          backgroundColor: "#252A34",
          borderTopLeftRadius: 12,
          borderTopRightRadius: 12,
          position: "absolute",
          overflow: "hidden",
        },
        tabBarActiveTintColor: "#fff",
        tabBarInactiveTintColor: "#aaa",
        headerStyle: {
          backgroundColor: "#F3F5F8",
        },
      }}
    >
      {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>
  );
}
