import React from 'react';
import { TouchableOpacity, View, Text } from 'react-native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { NavigatorScreenParams } from '@react-navigation/native';
import { DrawerNavigationProp } from '@react-navigation/drawer';
import Icon from 'react-native-vector-icons/Ionicons';
import { route, RouteParams } from '@utils';
import {
  DashboardScreen,
  AddLeadScreen,
  ProfileScreen,
  NotificationScreen,
  EditProfileScreen,
} from '@features';
import { LeadsStack, LeadsStackParamList } from './leadsStack';
import { CustomersStack, CustomersStackParamList } from './customersStack';
import { useTheme } from '@theme';
import { useAppSelector, RootState } from '@store';
import { getStyles } from './tabStack.styles';

export type DashboardStackParamList = {
  dashboardList: undefined;
  notifications: undefined;
};

export type AddLeadStackParamList = {
  addLeadForm: undefined;
};

export type ProfileStackParamList = {
  profileForm: undefined;
  editProfile: undefined;
};

export type TabStackParamList = {
  dashboard: NavigatorScreenParams<DashboardStackParamList> | undefined;
  leads: NavigatorScreenParams<LeadsStackParamList> | undefined;
  addLead: NavigatorScreenParams<AddLeadStackParamList> | undefined;
  customers: NavigatorScreenParams<CustomersStackParamList> | undefined;
  profile: NavigatorScreenParams<ProfileStackParamList> | undefined;
};

const Tab = createBottomTabNavigator<TabStackParamList>();

const DashboardStackNav = createNativeStackNavigator<DashboardStackParamList>();
const DashboardStack = () => {
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);
  const userData = useAppSelector((state: RootState) => state.auth.user_data);
  const { items: notificationItems, hasFetched } = useAppSelector((state: RootState) => state.notifications);
  
  // Calculate unread count from actual items if they've been fetched, otherwise fallback to userData's initial count
  const unreadCount = hasFetched
    ? notificationItems.filter(n => String(n.isread) === '0').length
    : parseInt(userData?.total_unread_notifications ?? '0', 10);

  return (
    <DashboardStackNav.Navigator
      screenOptions={{
        headerStyle: {
          backgroundColor: colors.header,
        },
        headerTitleStyle: {
          fontSize: 17,
          fontWeight: '700',
          color: colors.text,
        },
        headerTitleAlign: 'center',
        headerTintColor: colors.text,
        headerShadowVisible: false,
        statusBarTranslucent: false,
      }}>
      <DashboardStackNav.Screen
        name="dashboardList"
        component={DashboardScreen}
        options={({ navigation }) => ({
          headerTitle: 'Convex CRM',
          headerLeft: () => (
            <TouchableOpacity
              style={styles.drawerButton}
              activeOpacity={0.7}
              onPress={() => {
                const parentNav = navigation.getParent<DrawerNavigationProp<any>>();
                if (parentNav) {
                  parentNav.openDrawer();
                } else {
                  (navigation as any).openDrawer?.();
                }
              }}>
              <Icon name="menu-outline" size={20} color={colors.text} />
            </TouchableOpacity>
          ),
          headerRight: () => (
            <TouchableOpacity
              style={styles.notificationButton}
              activeOpacity={0.7}
              onPress={() => {
                // Navigate to notification screen if exists, or profile/other suitable route
                navigation.navigate(route.notifications);
              }}>
              <Icon name="notifications-outline" size={20} color='#EF4444' />
              {unreadCount > 0 ? (
                <View style={styles.badgeContainer}>
                  <Text style={styles.badgeText}>
                    {unreadCount > 99 ? '99+' : unreadCount}
                  </Text>
                </View>
              ) : null}
            </TouchableOpacity>
          ),
        })}
      />
      <DashboardStackNav.Screen
        name={route.notifications}
        component={NotificationScreen}
        options={{
          headerTitle: 'Notifications',
        }}
      />
    </DashboardStackNav.Navigator>
  );
};

const AddLeadStackNav = createNativeStackNavigator<AddLeadStackParamList>();
const AddLeadStack = () => {
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);
  return (
    <AddLeadStackNav.Navigator
      screenOptions={{
        headerStyle: {
          backgroundColor: colors.header,
        },
        headerTitleStyle: {
          fontSize: 17,
          fontWeight: '700',
          color: colors.text,
        },
        headerTitleAlign: 'center',
        headerTintColor: colors.text,
        headerShadowVisible: false,
        statusBarTranslucent: false,
      }}>
      <AddLeadStackNav.Screen
        name="addLeadForm"
        component={AddLeadScreen}
        options={({ navigation }) => ({
          headerTitle: 'Add Lead',
          headerLeft: () => (
            <TouchableOpacity
              style={styles.drawerButton}
              activeOpacity={0.7}
              onPress={() => {
                const parentNav = navigation.getParent<DrawerNavigationProp<any>>();
                if (parentNav) {
                  parentNav.openDrawer();
                } else {
                  (navigation as any).openDrawer?.();
                }
              }}>
              <Icon name="menu-outline" size={20} color={colors.text} />
            </TouchableOpacity>
          ),
        })}
      />
    </AddLeadStackNav.Navigator>
  );
};

const ProfileStackNav = createNativeStackNavigator<ProfileStackParamList>();
const ProfileStack = () => {
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);
  return (
    <ProfileStackNav.Navigator
      screenOptions={{
        headerStyle: {
          backgroundColor: colors.header,
        },
        headerTitleStyle: {
          fontSize: 17,
          fontWeight: '700',
          color: colors.text,
        },
        headerTitleAlign: 'center',
        headerTintColor: colors.text,
        headerShadowVisible: false,
        statusBarTranslucent: false,
      }}>
      <ProfileStackNav.Screen
        name="profileForm"
        component={ProfileScreen}
        options={({ navigation }) => ({
          headerTitle: 'Profile',
          headerLeft: () => (
            <TouchableOpacity
              style={styles.drawerButton}
              activeOpacity={0.7}
              onPress={() => {
                const parentNav = navigation.getParent<DrawerNavigationProp<any>>();
                if (parentNav) {
                  parentNav.openDrawer();
                } else {
                  (navigation as any).openDrawer?.();
                }
              }}>
              <Icon name="menu-outline" size={20} color={colors.text} />
            </TouchableOpacity>
          ),
          headerRight: () => (
            <TouchableOpacity
              onPress={() => navigation.navigate(route.editProfile)}
              style={{
                marginRight: 8,
                backgroundColor: colors.icon,
                width: 32,
                height: 32,
                borderRadius: 16,
                justifyContent: 'center',
                alignItems: 'center',
                shadowColor: colors.icon,
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.25,
                shadowRadius: 3.84,
                elevation: 3,
              }}
              activeOpacity={0.7}
              hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
              <Icon name="create-outline" size={16} color="#FFFFFF" />
            </TouchableOpacity>
          ),
        })}
      />
      <ProfileStackNav.Screen
        name={route.editProfile}
        component={EditProfileScreen}
        options={{
          headerTitle: 'Edit Profile',
        }}
      />
    </ProfileStackNav.Navigator>
  );
};

export const TabStack = () => {
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);

  return (
    <Tab.Navigator
      screenOptions={({ route: tabRoute }) => ({
        tabBarIcon: ({ focused, color }) => {
          if (tabRoute.name === route.addLead) {
            return (
              <View style={styles.addLeadButtonWrapper}>
                <Icon name="add" size={24} color="#FFFFFF" />
              </View>
            );
          }

          let iconName = 'square';
          if (tabRoute.name === route.dashboard) {
            iconName = focused ? 'grid' : 'grid-outline';
          } else if (tabRoute.name === route.leads) {
            iconName = focused ? 'funnel' : 'funnel-outline';
          } else if (tabRoute.name === route.customers) {
            iconName = focused ? 'people' : 'people-outline';
          } else if (tabRoute.name === route.profile) {
            iconName = focused ? 'person' : 'person-outline';
          }

          return (
            <View style={[styles.iconContainer, focused && styles.iconContainerFocused]}>
              <Icon name={iconName} size={20} color={color} />
            </View>
          );
        },
        tabBarActiveTintColor: colors.icon,
        tabBarInactiveTintColor: colors.textMuted,
        tabBarStyle: styles.tabBar,
        tabBarLabelStyle: styles.tabBarLabel,
        headerShown: false,
      })}>
      <Tab.Screen
        name={route.dashboard}
        component={DashboardStack}
        options={{
          tabBarLabel: 'Dashboard',
        }}
        listeners={({ navigation }) => ({
          tabPress: (e) => {
            e.preventDefault();
            navigation.navigate(route.dashboard, {
              screen: 'dashboardList',
            });
          },
        })}
      />
      <Tab.Screen
        name={route.leads}
        component={LeadsStack}
        options={{
          tabBarLabel: 'Leads',
        }}
        listeners={({ navigation }) => ({
          tabPress: (e) => {
            e.preventDefault();
            navigation.navigate(route.leads, {
              screen: route.leadsList,
            });
          },
        })}
      />
      <Tab.Screen
        name={route.addLead}
        component={AddLeadStack}
        options={{
          tabBarLabel: 'Add Lead',
        }}
        listeners={({ navigation }) => ({
          tabPress: (e) => {
            e.preventDefault();
            navigation.navigate(route.addLead, {
              screen: 'addLeadForm',
            });
          },
        })}
      />
      <Tab.Screen
        name={route.customers}
        component={CustomersStack}
        options={{
          tabBarLabel: 'Customers',
        }}
        listeners={({ navigation }) => ({
          tabPress: (e) => {
            e.preventDefault();
            navigation.navigate(route.customers, {
              screen: route.customersList,
            });
          },
        })}
      />
      <Tab.Screen
        name={route.profile}
        component={ProfileStack}
        options={{
          tabBarLabel: 'Profile',
        }}
        listeners={({ navigation }) => ({
          tabPress: (e) => {
            e.preventDefault();
            navigation.navigate(route.profile, {
              screen: 'profileForm',
            });
          },
        })}
      />
    </Tab.Navigator>
  );
};
