import { Tabs, useSegments } from "expo-router";

import { HapticTab } from "@/components/haptic-tab";
import { IconSymbol } from "@/components/ui/icon-symbol";
import { queryProfile } from "@/controller/AuthController";
import { useI18n } from "@/hooks/use-i18n";
import { useThemeContext } from "@/hooks/use-theme-context";
import { addUserStorage } from "@/utils/storage";
import { useEffect, useRef } from "react";

export default function TabLayout() {
  const { colors, colorScheme } = useThemeContext();
  const segments = useSegments() as string[];
  const prev = useRef<string | null>(null);
  const currentSegment = segments[1] ?? segments[segments.length - 1] ?? null;
  const { t } = useI18n();
  useEffect(() => {
    if (prev.current !== currentSegment) {
      // console.log("Tab changed ->", { from: prev.current, to: currentSegment });
      // TODO: xử lý khi chuyển tab ở đây
      if (prev.current === "(tabs)" && currentSegment !== "(tabs)") {
        // stopEvents();
        // console.log("Stop events");
      } else if (prev.current !== "(tabs)" && currentSegment === "(tabs)") {
        // we came back into the tabs group — restart polling
        // startEvents();
        // console.log("start events");
      }
      prev.current = currentSegment;
    }
  }, [currentSegment]);

  useEffect(() => {
    const getUserProfile = async () => {
      try {
        const resp = await queryProfile();
        if (resp.data && resp.status === 200) {
          await addUserStorage(
            resp.data.id || "",
            resp.data.metadata?.user_type || ""
          );
        }
      } catch (error) {
        console.error("Error when get Profile: ", error);
      }
    };
    getUserProfile();
  }, []);

  return (
    <Tabs
      screenOptions={{
        tabBarActiveTintColor: colors.tint,
        headerShown: false,
        tabBarButton: HapticTab,
        // Set tab bar styles based on theme - prevents white flash
        tabBarStyle: {
          backgroundColor: colors.background,
          borderTopColor: colors.separator,
        },
        // Set screen content background
        sceneStyle: {
          backgroundColor: colors.background,
        },
      }}
    >
      <Tabs.Screen
        name="index"
        options={{
          title: t("navigation.home"),
          tabBarIcon: ({ color }) => (
            <IconSymbol size={28} name="map.fill" color={color} />
          ),
        }}
      />
      <Tabs.Screen
        name="diary"
        options={{
          title: t("navigation.diary"),
          tabBarIcon: ({ color }) => (
            <IconSymbol size={28} name="book.closed.fill" color={color} />
          ),
        }}
      />
      <Tabs.Screen
        name="manager"
        options={{
          title: t("navigation.manager"),
          tabBarIcon: ({ color }) => (
            <IconSymbol
              size={28}
              name="square.stack.3d.up.fill"
              color={color}
            />
          ),
        }}
      />

      <Tabs.Screen
        name="warning"
        options={{
          title: t("navigation.warning"),
          tabBarIcon: ({ color }) => (
            <IconSymbol size={28} name="bell.fill" color={color} />
          ),
        }}
      />
      <Tabs.Screen
        name="setting"
        options={{
          title: t("navigation.setting"),
          tabBarIcon: ({ color }) => (
            <IconSymbol size={28} name="gear" color={color} />
          ),
        }}
      />
    </Tabs>
  );
}
