import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import type { NavigatorScreenParams } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../theme/colors';
import { fontSizes } from '../theme/typography';
import { useAuthStore } from '../stores/auth.store';
import { LoginScreen } from '../screens/auth';
import { HomeScreen } from '../screens/home';
import { ScheduleScreen } from '../screens/schedule';
import { TrainingDetailScreen } from '../screens/schedule/training-detail';
import { CreateTrainingScreen } from '../screens/schedule/create-training';
import { ClientsScreen } from '../screens/clients';
import { ClientDetailScreen } from '../screens/clients/client-detail';
import type { ClientsStackParamList } from '../screens/clients/types';
import { FunnelScreen } from '../screens/funnel';
import { FunnelActionScreen } from '../screens/funnel/funnel-action';
import { AssignClientScreen } from '../screens/funnel/assign-client';
import { MoreScreen } from '../screens/more';
import { StatsScreen } from '../screens/stats';
import { RatingScreen } from '../screens/rating';
import { SalesScreen } from '../screens/sales';
import { CreateSaleScreen } from '../screens/sales/create-sale';
import { CoordinatorScreen } from '../screens/coordinator';
import { CallLogScreen } from '../screens/sip';
import { SleepingClientsScreen } from '../screens/sleeping';
import { WorkScheduleScreen } from '../screens/work-schedule';
import { NotificationsScreen } from '../screens/notifications';
import { BookingListScreen } from '../screens/booking';
import { BookingDetailScreen } from '../screens/booking/booking-detail';
import { GroupEventsScreen } from '../screens/booking/group-events';
import { GroupEventDetailScreen } from '../screens/booking/group-event-detail';
import type { ScheduleStackParamList } from '../screens/schedule/types';

export type AuthStackParamList = {
  Login: undefined;
};

export type FunnelStackParamList = {
  FunnelList: undefined;
  FunnelAction: { clientId: string };
  AssignClient: { clientId: string; isTransfer?: boolean };
};

export type MoreStackParamList = {
  MoreMain: undefined;
  Stats: undefined;
  Rating: undefined;
  SalesList: undefined;
  CreateSale: undefined;
  Coordinator: undefined;
  CallLog: undefined;
  SleepingClients: undefined;
  WorkSchedule: undefined;
  Notifications: undefined;
  BookingList: undefined;
  BookingDetail: { recordId: string };
  GroupEvents: undefined;
  GroupEventDetail: { eventId: string };
};

export type MainTabParamList = {
  Home: undefined;
  ScheduleTab: NavigatorScreenParams<ScheduleStackParamList>;
  Funnel: NavigatorScreenParams<FunnelStackParamList>;
  Clients: NavigatorScreenParams<ClientsStackParamList>;
  More: NavigatorScreenParams<MoreStackParamList>;
};

const AuthStack = createNativeStackNavigator<AuthStackParamList>();
const FunnelStack = createNativeStackNavigator<FunnelStackParamList>();
const ClientsStackNav = createNativeStackNavigator<ClientsStackParamList>();
const ScheduleStackNav = createNativeStackNavigator<ScheduleStackParamList>();
const MoreStack = createNativeStackNavigator<MoreStackParamList>();
const MainTab = createBottomTabNavigator<MainTabParamList>();

/** Stack header options — read colors at render time so theme changes apply */
function useHeaderOptions() {
  return {
    headerStyle: {
      backgroundColor: colors.card,
      shadowColor: colors.black,
      shadowOffset: { width: 0, height: 1 },
      shadowOpacity: 0.05,
      shadowRadius: 4,
      elevation: 2,
    },
    headerTitleStyle: {
      fontSize: fontSizes.subtitle,
      fontWeight: '600' as const,
      color: colors.text,
    },
    headerTintColor: colors.text,
    headerBackTitle: 'Назад',
  };
}

function ScheduleNavigator(): React.JSX.Element {
  const headerOptions = useHeaderOptions();
  return (
    <ScheduleStackNav.Navigator screenOptions={headerOptions}>
      <ScheduleStackNav.Screen
        name="ScheduleMain"
        component={ScheduleScreen}
        options={{ title: 'Расписание' }}
      />
      <ScheduleStackNav.Screen
        name="TrainingDetail"
        component={TrainingDetailScreen}
        options={{ title: 'Тренировка' }}
      />
      <ScheduleStackNav.Screen
        name="CreateTraining"
        component={CreateTrainingScreen}
        options={{ title: 'Новая тренировка' }}
      />
    </ScheduleStackNav.Navigator>
  );
}

function FunnelNavigator(): React.JSX.Element {
  const headerOptions = useHeaderOptions();
  return (
    <FunnelStack.Navigator screenOptions={headerOptions}>
      <FunnelStack.Screen
        name="FunnelList"
        component={FunnelScreen}
        options={{ title: 'Воронка' }}
      />
      <FunnelStack.Screen
        name="FunnelAction"
        component={FunnelActionScreen}
        options={{ title: 'Карточка клиента' }}
      />
      <FunnelStack.Screen
        name="AssignClient"
        component={AssignClientScreen}
        options={{ title: 'Назначение' }}
      />
    </FunnelStack.Navigator>
  );
}

function ClientsNavigator(): React.JSX.Element {
  const headerOptions = useHeaderOptions();
  return (
    <ClientsStackNav.Navigator screenOptions={headerOptions}>
      <ClientsStackNav.Screen
        name="ClientsList"
        component={ClientsScreen}
        options={{ title: 'Клиенты' }}
      />
      <ClientsStackNav.Screen
        name="ClientDetail"
        component={ClientDetailScreen}
        options={{ title: 'Карточка клиента' }}
      />
    </ClientsStackNav.Navigator>
  );
}

function MoreNavigator(): React.JSX.Element {
  const headerOptions = useHeaderOptions();
  return (
    <MoreStack.Navigator screenOptions={headerOptions}>
      <MoreStack.Screen name="MoreMain" component={MoreScreen} options={{ title: 'Ещё' }} />
      <MoreStack.Screen name="Stats" component={StatsScreen} options={{ title: 'Статистика' }} />
      <MoreStack.Screen name="Rating" component={RatingScreen} options={{ title: 'Рейтинг' }} />
      <MoreStack.Screen name="SalesList" component={SalesScreen} options={{ title: 'Продажи' }} />
      <MoreStack.Screen
        name="CreateSale"
        component={CreateSaleScreen}
        options={{ title: 'Новая продажа' }}
      />
      <MoreStack.Screen
        name="Coordinator"
        component={CoordinatorScreen}
        options={{ title: 'Координатор' }}
      />
      <MoreStack.Screen name="CallLog" component={CallLogScreen} options={{ title: 'Звонки' }} />
      <MoreStack.Screen
        name="SleepingClients"
        component={SleepingClientsScreen}
        options={{ title: 'Спящие клиенты' }}
      />
      <MoreStack.Screen
        name="WorkSchedule"
        component={WorkScheduleScreen}
        options={{ title: 'График работы' }}
      />
      <MoreStack.Screen
        name="Notifications"
        component={NotificationsScreen}
        options={{ title: 'Уведомления' }}
      />
      <MoreStack.Screen
        name="BookingList"
        component={BookingListScreen}
        options={{ title: 'Мои записи' }}
      />
      <MoreStack.Screen
        name="BookingDetail"
        component={BookingDetailScreen}
        options={{ title: 'Запись' }}
      />
      <MoreStack.Screen
        name="GroupEvents"
        component={GroupEventsScreen}
        options={{ title: 'Групповые занятия' }}
      />
      <MoreStack.Screen
        name="GroupEventDetail"
        component={GroupEventDetailScreen}
        options={{ title: 'Групповое занятие' }}
      />
    </MoreStack.Navigator>
  );
}

type IoniconsName = React.ComponentProps<typeof Ionicons>['name'];

function TabIcon({ name, focused }: { name: IoniconsName; focused: boolean }): React.JSX.Element {
  return <Ionicons name={name} size={22} color={focused ? colors.primary : colors.textMuted} />;
}

function AuthNavigator(): React.JSX.Element {
  return (
    <AuthStack.Navigator screenOptions={{ headerShown: false }}>
      <AuthStack.Screen name="Login" component={LoginScreen} />
    </AuthStack.Navigator>
  );
}

function MainNavigator(): React.JSX.Element {
  const insets = useSafeAreaInsets();
  const bottomPadding = Math.max(insets.bottom, 8);
  const headerOptions = useHeaderOptions();

  return (
    <MainTab.Navigator
      screenOptions={{
        tabBarActiveTintColor: colors.primary,
        tabBarInactiveTintColor: colors.textMuted,
        tabBarStyle: {
          backgroundColor: colors.card,
          borderTopColor: colors.border,
          borderTopWidth: 1,
          paddingTop: 4,
          paddingBottom: bottomPadding,
          height: 56 + bottomPadding,
        },
        tabBarLabelStyle: {
          fontSize: fontSizes.caption,
          fontWeight: '500',
        },
        ...headerOptions,
      }}
    >
      <MainTab.Screen
        name="Home"
        component={HomeScreen}
        options={{
          title: 'Главная',
          tabBarIcon: ({ focused }) => (
            <TabIcon name={focused ? 'home' : 'home-outline'} focused={focused} />
          ),
        }}
      />
      <MainTab.Screen
        name="ScheduleTab"
        component={ScheduleNavigator}
        options={{
          title: 'Расписание',
          headerShown: false,
          tabBarIcon: ({ focused }) => (
            <TabIcon name={focused ? 'calendar' : 'calendar-outline'} focused={focused} />
          ),
        }}
      />
      <MainTab.Screen
        name="Funnel"
        component={FunnelNavigator}
        options={{
          title: 'Воронка',
          headerShown: false,
          tabBarIcon: ({ focused }) => (
            <TabIcon name={focused ? 'funnel' : 'funnel-outline'} focused={focused} />
          ),
        }}
      />
      <MainTab.Screen
        name="Clients"
        component={ClientsNavigator}
        options={{
          title: 'Клиенты',
          headerShown: false,
          tabBarIcon: ({ focused }) => (
            <TabIcon name={focused ? 'people' : 'people-outline'} focused={focused} />
          ),
        }}
      />
      <MainTab.Screen
        name="More"
        component={MoreNavigator}
        options={{
          title: 'Ещё',
          headerShown: false,
          tabBarIcon: ({ focused }) => (
            <TabIcon
              name={focused ? 'ellipsis-horizontal' : 'ellipsis-horizontal-outline'}
              focused={focused}
            />
          ),
        }}
      />
    </MainTab.Navigator>
  );
}

export function AppNavigation(): React.JSX.Element {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated);

  return (
    <NavigationContainer>
      {isAuthenticated ? <MainNavigator /> : <AuthNavigator />}
    </NavigationContainer>
  );
}
