import React from "react";
import { Platform } from "react-native";
import { Redirect, Tabs } from "expo-router";
import { NativeTabs } from "expo-router/unstable-native-tabs";
import Ionicons from "@react-native-vector-icons/ionicons";

import { useAuth } from "@/src/auth";
import { usesNativeTabs } from "@/src/navigation";
import { useTheme } from "@/src/theme";
import { fs, isTV } from "@/src/ui";

const TABS = [
  { name: "index", title: "Início", icon: "home", sf: "house.fill" },
  { name: "live", title: "Ao Vivo", icon: "radio", sf: "dot.radiowaves.left.and.right" },
  { name: "mylist", title: "Minha Lista", icon: "heart", sf: "heart.fill" },
  { name: "vpn", title: "VPN", icon: "shield-checkmark", sf: "lock.shield.fill" },
] as const;

export default function TabsLayout() {
  const { colors } = useTheme();
  const { user, loading } = useAuth();
  if (!loading && !user) return <Redirect href="/login" />;

  if (usesNativeTabs) {
    return (
      <NativeTabs tintColor={colors.brandPrimary}>
        {TABS.map((t) => (
          <NativeTabs.Trigger key={t.name} name={t.name}>
            <NativeTabs.Trigger.Icon sf={t.sf} />
            <NativeTabs.Trigger.Label>{t.title}</NativeTabs.Trigger.Label>
          </NativeTabs.Trigger>
        ))}
      </NativeTabs>
    );
  }

  return (
    <Tabs
      screenOptions={{
        headerShown: false,
        // TV: side navigation rail (D-pad friendly); phones: bottom tabs.
        tabBarPosition: isTV ? "left" : "bottom",
        tabBarActiveTintColor: colors.onSurface,
        tabBarInactiveTintColor: colors.muted,
        tabBarActiveBackgroundColor: isTV ? colors.brandTertiary : undefined,
        tabBarStyle: { backgroundColor: colors.surfaceSecondary, borderTopColor: colors.border, ...(Platform.OS === "web" ? { height: 64 } : {}) },
        ...(isTV ? {} : { tabBarItemStyle: { alignSelf: "center" } }),
        tabBarLabelStyle: { fontSize: fs(11), fontWeight: "600" },
        sceneStyle: { backgroundColor: colors.surface },
      }}
    >
      {TABS.map((t) => (
        <Tabs.Screen
          key={t.name}
          name={t.name}
          options={{
            title: t.title,
            tabBarButtonTestID: `tab-${t.name}`,
            tabBarIcon: ({ color, focused }) => (
              <Ionicons name={(focused ? t.icon : `${t.icon}-outline`) as any} size={isTV ? 30 : 22} color={focused ? colors.brandPrimary : color} />
            ),
          }}
        />
      ))}
    </Tabs>
  );
}
