/**
 * Bottom tabs: Home · Explore · [CREATE FAB] · Messages · Profile
 * The center button is a big purple gradient FAB that opens CreateRoom on the
 * root stack (named 'Root').
 */
import React from 'react';
import {Platform, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import type {BottomTabBarProps} from '@react-navigation/bottom-tabs';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {COLORS} from '../theme/colors';
import {SHADOW} from '../theme/spacing';
import {Gradient} from '../components/Gradient';
import {HomeScreen} from '../screens/HomeScreen';
import {ExploreRoomsScreen} from '../screens/ExploreRoomsScreen';
import {PrivateChatScreen} from '../screens/PrivateChatScreen';
import {UserProfileScreen} from '../screens/UserProfileScreen';
import type {TabParamList} from '../types/navigation';

const Tab = createBottomTabNavigator<TabParamList>();

const ICONS: Record<string, {focused: string; idle: string}> = {
  Home: {focused: 'home', idle: 'home-outline'},
  Explore: {focused: 'compass', idle: 'compass-outline'},
  Messages: {focused: 'chatbubbles', idle: 'chatbubbles-outline'},
  Profile: {focused: 'person', idle: 'person-outline'},
};

function AuraTabBar({state, descriptors, navigation}: BottomTabBarProps) {
  return (
    <SafeAreaView edges={['bottom']} style={styles.safe}>
      <View style={styles.bar}>
        {state.routes.map((route, index) => {
          const {options} = descriptors[route.key];
          const focused = state.index === index;
          const label = (options.title ?? route.name) as string;
          const icons = ICONS[label] ?? {focused: 'ellipse', idle: 'ellipse-outline'};
          const color = focused ? COLORS.purple : COLORS.secondaryText;

          const onPress = () => {
            const event = navigation.emit({type: 'tabPress', target: route.key, canPreventDefault: true});
            if (!focused && !event.defaultPrevented) navigation.navigate(route.name as never);
          };

          return (
            <TouchableOpacity
              key={route.key}
              accessibilityRole="button"
              accessibilityState={focused ? {selected: true} : {}}
              onPress={onPress}
              style={[styles.tab, index >= 2 && styles.tabAfterFab]}>
              <Icon name={focused ? icons.focused : icons.idle} size={23} color={color} />
              <Text style={[styles.label, {color}]}>{label}</Text>
              {focused && <View style={styles.indicator} />}
            </TouchableOpacity>
          );
        })}

        {/* Center FAB — opens CreateRoom on the Root stack */}
        <TouchableOpacity
          accessibilityLabel="Create room"
          style={styles.fab}
          activeOpacity={0.85}
          onPress={() => navigation.navigate('Root' as never, {screen: 'CreateRoom'} as never)}>
          <Gradient style={styles.fabGrad} angle={135}>
            <Icon name="add" size={30} color={COLORS.white} />
          </Gradient>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

export function TabNavigator(): React.JSX.Element {
  return (
    <Tab.Navigator
      tabBar={props => <AuraTabBar {...props} />}
      screenOptions={{headerShown: false, lazy: true}}>
      <Tab.Screen name="Home" component={HomeScreen} options={{title: 'Home'}} />
      <Tab.Screen name="Explore" component={ExploreRoomsScreen} options={{title: 'Explore'}} />
      <Tab.Screen name="Messages" component={PrivateChatScreen} options={{title: 'Messages'}} />
      <Tab.Screen name="Profile">
        {() => <UserProfileScreen userId="me" />}
      </Tab.Screen>
    </Tab.Navigator>
  );
}

const styles = StyleSheet.create({
  safe: {backgroundColor: COLORS.darkBg},
  bar: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 64,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: COLORS.divider,
  },
  tab: {flex: 1, alignItems: 'center', justifyContent: 'center', gap: 2},
  tabAfterFab: {},
  label: {fontSize: 10, fontWeight: '600'},
  indicator: {
    position: 'absolute',
    top: -1,
    width: 22,
    height: 3,
    borderRadius: 3,
    backgroundColor: COLORS.magenta,
  },
  fab: {
    position: 'absolute',
    left: '50%',
    top: Platform.OS === 'android' ? -26 : -30,
    marginLeft: -30,
    width: 60,
    height: 60,
    borderRadius: 30,
    ...SHADOW.glowPurple,
  },
  fabGrad: {
    flex: 1,
    borderRadius: 30,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 3,
    borderColor: COLORS.darkBg,
  },
});
