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 { DrawerNavigationProp } from '@react-navigation/drawer';
import Icon from 'react-native-vector-icons/Ionicons';
import { route, RouteParams } from '@utils';
import {
  DashboardScreen,
  AddLeadScreen,
  ProfileScreen,
  NotificationScreen,
} from '@features';
import { LeadsStack } from './leadsStack';
import { CustomersStack } from './customersStack';
import { useTheme } from '@theme';
import { useAppSelector, RootState } from '@store';
import { getStyles } from './tabStack.styles';

export type TabStackParamList = Pick<
  RouteParams,
  'dashboard' | 'leads' | 'addLead' | 'customers' | 'profile'
>;

const Tab = createBottomTabNavigator<TabStackParamList>();

const DashboardStackNav = createNativeStackNavigator();
const DashboardStack = () => {
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);
  const userData = useAppSelector((state: RootState) => state.auth.user_data);
  const unreadCount = 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,
      }}>
      <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();
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,
      }}>
      <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();
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,
      }}>
      <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>
          ),
        })}
      />
    </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',
        }}
      />
      <Tab.Screen
        name={route.leads}
        component={LeadsStack}
        options={{
          tabBarLabel: 'Leads',
        }}
      />
      <Tab.Screen
        name={route.addLead}
        component={AddLeadStack}
        options={{
          tabBarLabel: 'Add Lead',
        }}
      />
      <Tab.Screen
        name={route.customers}
        component={CustomersStack}
        options={{
          tabBarLabel: 'Customers',
        }}
      />
      <Tab.Screen
        name={route.profile}
        component={ProfileStack}
        options={{
          tabBarLabel: 'Profile',
        }}
      />
    </Tab.Navigator>
  );
};
