import React, {useCallback, useState} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {TVTouchable as TouchableOpacity} from '../components/common/TVTouchable';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {BottomTabBarProps} from '@react-navigation/bottom-tabs';
import {useNavigation} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {RootStackParamList, BottomTabParamList} from './types';
import {colors} from '../utils/colors';
import {IS_PHONE, SIDEBAR_W} from '../utils/dimensions';
import {IS_TV, TV_FOCUS_COLOR, TV_FOCUS_BORDER} from '../utils/tv';
import SearchScreen from '../screens/SearchScreen';
import DiscoverScreen from '../screens/DiscoverScreen';
import LibraryScreen from '../screens/LibraryScreen';
import AddonsScreen from '../screens/AddonsScreen';

const Tab = createBottomTabNavigator<BottomTabParamList>();

const TAB_ICONS: Record<
  string,
  {focused: string; unfocused: string; label: string}
> = {
  Discover: {focused: 'compass', unfocused: 'compass-outline', label: 'Discover'},
  Search: {focused: 'magnify', unfocused: 'magnify', label: 'Search'},
  Library: {focused: 'bookmark', unfocused: 'bookmark-outline', label: 'Library'},
  Addons: {focused: 'puzzle', unfocused: 'puzzle-outline', label: 'Addons'},
};

/* ─── Focusable sidebar tab button (TV D-pad) ─── */
function SideTabButton({
  isFocused,
  iconName,
  color,
  onPress,
  hasTVPreferredFocus,
}: {
  isFocused: boolean;
  iconName: string;
  color: string;
  onPress: () => void;
  hasTVPreferredFocus?: boolean;
}) {
  const [tvFocused, setTvFocused] = useState(false);
  return (
    <TouchableOpacity
      style={[
        sideStyles.tabBtn,
        isFocused && sideStyles.tabBtnActive,
        IS_TV && tvFocused && sideStyles.tabBtnTVFocus,
      ]}
      onPress={onPress}
      activeOpacity={0.7}
      focusable={IS_TV || undefined}
      hasTVPreferredFocus={hasTVPreferredFocus}
      onFocus={IS_TV ? () => setTvFocused(true) : undefined}
      onBlur={IS_TV ? () => setTvFocused(false) : undefined}>
      {isFocused && <View style={sideStyles.activeBar} />}
      <Icon name={iconName} size={24} color={tvFocused ? TV_FOCUS_COLOR : color} />
    </TouchableOpacity>
  );
}

/* ─── Sidebar (TV / Tablet) ─── */
function SideTabBar({state, descriptors, navigation}: BottomTabBarProps) {
  const rootNav = useNavigation<StackNavigationProp<RootStackParamList>>();

  return (
    <View style={sideStyles.sidebar}>
      {/* App logo */}
      <View style={sideStyles.logoContainer}>
        <Icon name="play-circle" size={30} color={colors.primary} />
      </View>

      <View style={sideStyles.divider} />

      {/* Tab buttons */}
      {state.routes.map((route, index) => {
        const isFocused = state.index === index;
        const iconSet = TAB_ICONS[route.name];
        const color = isFocused ? colors.primary : colors.textMuted;

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

        return (
          <SideTabButton
            key={route.key}
            isFocused={isFocused}
            iconName={isFocused ? iconSet.focused : iconSet.unfocused}
            color={color}
            onPress={onPress}
            hasTVPreferredFocus={IS_TV && index === 0}
          />
        );
      })}

      {/* Push settings to bottom */}
      <View style={sideStyles.spacer} />

      {/* Settings button */}
      <SideTabButton
        isFocused={false}
        iconName="cog-outline"
        color={colors.textMuted}
        onPress={() => rootNav.navigate('Settings')}
      />

      <View style={sideStyles.bottomPad} />
    </View>
  );
}

/* ─── Bottom Tab Bar (Phone) ─── */
function BottomTabBarMobile({state, navigation}: BottomTabBarProps) {
  const rootNav = useNavigation<StackNavigationProp<RootStackParamList>>();

  const allItems = [
    ...state.routes.map((route, index) => ({
      key: route.key,
      name: route.name,
      index,
      isSettings: false,
    })),
    {key: 'settings', name: 'Settings', index: -1, isSettings: true},
  ];

  return (
    <View style={bottomStyles.bar}>
      {allItems.map(item => {
        const isFocused = !item.isSettings && state.index === item.index;
        const iconSet = item.isSettings
          ? {focused: 'cog', unfocused: 'cog-outline', label: 'Settings'}
          : TAB_ICONS[item.name];
        const color = isFocused ? colors.primary : colors.textMuted;

        const onPress = () => {
          if (item.isSettings) {
            rootNav.navigate('Settings');
            return;
          }
          const event = navigation.emit({
            type: 'tabPress',
            target: item.key,
            canPreventDefault: true,
          });
          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(item.name as keyof BottomTabParamList);
          }
        };

        return (
          <TouchableOpacity
            key={item.key}
            style={bottomStyles.tabItem}
            onPress={onPress}
            activeOpacity={0.7}>
            <Icon
              name={isFocused ? iconSet.focused : iconSet.unfocused}
              size={22}
              color={color}
            />
            <Text style={[bottomStyles.label, isFocused && bottomStyles.labelActive]}>
              {iconSet.label}
            </Text>
            {isFocused && <View style={bottomStyles.activeDot} />}
          </TouchableOpacity>
        );
      })}
    </View>
  );
}

export default function TabNavigator() {
  return (
    <Tab.Navigator
      tabBar={props =>
        IS_PHONE ? (
          <BottomTabBarMobile {...props} />
        ) : (
          <SideTabBar {...props} />
        )
      }
      sceneContainerStyle={{marginLeft: IS_PHONE ? 0 : SIDEBAR_W}}
      screenOptions={{headerShown: false}}>
      <Tab.Screen name="Discover" component={DiscoverScreen} />
      <Tab.Screen name="Search" component={SearchScreen} />
      <Tab.Screen name="Library" component={LibraryScreen} />
      <Tab.Screen name="Addons" component={AddonsScreen} />
    </Tab.Navigator>
  );
}

/* ─── Sidebar Styles ─── */
const sideStyles = StyleSheet.create({
  sidebar: {
    position: 'absolute',
    left: 0,
    top: 0,
    bottom: 0,
    width: SIDEBAR_W,
    backgroundColor: colors.tabBar,
    borderRightWidth: 0.5,
    borderRightColor: colors.border,
    alignItems: 'center',
    paddingTop: 42,
    zIndex: 100,
    elevation: 24,
    shadowColor: '#000',
    shadowOffset: {width: 3, height: 0},
    shadowOpacity: 0.35,
    shadowRadius: 8,
  },
  logoContainer: {
    width: SIDEBAR_W,
    height: 52,
    justifyContent: 'center',
    alignItems: 'center',
  },
  divider: {
    width: 32,
    height: 1,
    backgroundColor: colors.border,
    marginBottom: 8,
  },
  tabBtn: {
    width: SIDEBAR_W,
    height: 54,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
  },
  tabBtnActive: {
    backgroundColor: colors.primary + '1A',
  },
  tabBtnTVFocus: {
    backgroundColor: TV_FOCUS_COLOR + '25',
    borderWidth: TV_FOCUS_BORDER,
    borderColor: TV_FOCUS_COLOR,
  },
  activeBar: {
    position: 'absolute',
    left: 0,
    top: 10,
    bottom: 10,
    width: 3,
    borderRadius: 2,
    backgroundColor: colors.primary,
  },
  spacer: {flex: 1},
  bottomPad: {height: 24},
});

/* ─── Bottom Bar Styles ─── */
const bottomStyles = StyleSheet.create({
  bar: {
    flexDirection: 'row',
    height: 56,
    backgroundColor: colors.tabBar,
    borderTopWidth: 0.5,
    borderTopColor: colors.border,
    paddingBottom: 2,
  },
  tabItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative',
    paddingTop: 6,
  },
  label: {
    fontSize: 10,
    fontWeight: '500',
    color: colors.textMuted,
    marginTop: 3,
  },
  labelActive: {
    color: colors.primary,
    fontWeight: '700',
  },
  activeDot: {
    position: 'absolute',
    top: 3,
    width: 4,
    height: 4,
    borderRadius: 2,
    backgroundColor: colors.primary,
  },
});
