import React, { createContext, useContext, useEffect, useState } from 'react';
import { Linking } from 'react-native';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import { storage, StoreType } from 'src/storage';

interface NavigationContextType {
  handleDeepLink: () => Promise<void>;
}

const NavigationContext = createContext<NavigationContextType | null>(null);

const parseURL = (url: string) => {
  const parsedUrl = new URL(url);
  const path = parsedUrl.pathname;
  const queryParams = Object.fromEntries(parsedUrl.searchParams.entries());
  return { path, queryParams };
};

export const useNavigationContext = () => useContext(NavigationContext);

const resetTo = (routes: any[]) =>
  CommonActions.reset({
    index: 1,
    routes: [
      {
        name: 'DrawerApp',
        state: { routes },
      },
    ],
  });

export const NavigationProvider = ({ children }: { children: React.ReactNode }) => {
  const navigation = useNavigation();
  const token = storage.get('token', StoreType.STRING);
  const [initialUrlProcessed, setInitialUrlProcessed] = useState(false);

  const handleRegion = (
    path: string,
    type: 'nm' | 'dare',
  ) => {
    const [, , regionId] = path.split('/');

    navigation.dispatch(
      resetTo([
        {
          name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
          state: {
            routes: [
              { name: NAVIGATION_PAGES.TRAVELS_TAB },
              {
                name:
                  type === 'nm'
                    ? NAVIGATION_PAGES.REGIONS
                    : NAVIGATION_PAGES.DARE,
              },
              {
                name: NAVIGATION_PAGES.REGION_PREVIEW,
                params: {
                  regionId,
                  isTravelsScreen: true,
                  type,
                  disabled: !token,
                },
              },
            ],
          },
        },
      ]),
    );
  };

  const deepLinkHandlers: Record<
    string,
    (path: string) => void
  > = {
    '/profile': (path) => {
      if (!token) return;
      const [, , userId] = path.split('/');
      navigation.navigate(...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId }] as never));
    },

    '/event': (path) => {
      const [, , eventUrl] = path.split('/');
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_EVENTS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.EVENTS },
                {
                  name: NAVIGATION_PAGES.EVENT,
                  params: { url: eventUrl },
                },
              ],
            },
          },
        ]),
      );
    },

    '/map': (path) => {
      const segments = path.split('/');
      let lon: string | undefined;
      let lat: string | undefined;

      segments.forEach((segment) => {
        if (segment.startsWith('lon=')) {
          lon = segment.replace('lon=', '');
        } else if (segment.startsWith('lat=')) {
          lat = segment.replace('lat=', '');
        }
      });

      if (!lon || !lat) return;

      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_MAP_TAB,
            state: {
              routes: [
                {
                  name: NAVIGATION_PAGES.MAP_TAB,
                  params: { lon, lat },
                },
              ],
            },
          },
        ]),
      );
    },

    '/messages': () => {
      if (!token) return;
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_MESSAGES_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.CHATS_LIST },
              ],
            },
          },
        ]),
      );
    },

    '/lpi': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                { name: NAVIGATION_PAGES.LPI_RANKING },
              ],
            },
          },
        ]),
      ),

    '/master-ranking': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                {
                  name: NAVIGATION_PAGES.MASTER_RANKING,
                },
              ],
            },
          },
        ]),
      ),

    '/travellers-in-history': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                { name: NAVIGATION_PAGES.IN_HISTORY },
              ],
            },
          },
        ]),
      ),

    '/triumphs': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                { name: NAVIGATION_PAGES.TRIUMPHS },
              ],
            },
          },
        ]),
      ),

    '/statistics': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                { name: NAVIGATION_PAGES.STATISTICS },
              ],
            },
          },
        ]),
      ),

    '/in-memoriam': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                { name: NAVIGATION_PAGES.IN_MEMORIAM },
              ],
            },
          },
        ]),
      ),

    '/series-ranking': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                {
                  name: NAVIGATION_PAGES.SERIES_RANKING,
                },
              ],
            },
          },
        ]),
      ),

    '/un-masters': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                { name: NAVIGATION_PAGES.UN_MASTERS },
              ],
            },
          },
        ]),
      ),

    '/my-friends': () => {
      if (!token) return;
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELLERS_TAB },
                { name: NAVIGATION_PAGES.MY_FRIENDS },
              ],
            },
          },
        ]),
      );
    },

    '/fixers': () => {
      if (!token) return;
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELS_TAB },
                { name: NAVIGATION_PAGES.FIXERS },
              ],
            },
          },
        ]),
      );
    },

    '/earth': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELS_TAB },
                { name: NAVIGATION_PAGES.EARTH },
              ],
            },
          },
        ]),
      ),

    '/series': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELS_TAB },
                { name: NAVIGATION_PAGES.SERIES },
              ],
            },
          },
        ]),
      ),

    '/countries': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELS_TAB },
                { name: NAVIGATION_PAGES.COUNTRIES },
              ],
            },
          },
        ]),
      ),

    '/regions': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELS_TAB },
                { name: NAVIGATION_PAGES.REGIONS },
              ],
            },
          },
        ]),
      ),

    '/dare': () =>
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELS_TAB },
                { name: NAVIGATION_PAGES.DARE },
              ],
            },
          },
        ]),
      ),

    '/photos': () => {
      if (!token) return;
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRAVELS_TAB },
                { name: NAVIGATION_PAGES.PHOTOS },
              ],
            },
          },
        ]),
      );
    },

    '/trips': () => {
      if (!token) return;
      navigation.dispatch(
        resetTo([
          {
            name: NAVIGATION_PAGES.IN_APP_TRIPS_TAB,
            state: {
              routes: [
                { name: NAVIGATION_PAGES.TRIPS_2025 },
              ],
            },
          },
        ]),
      );
    },

    '/region_mqp': (path) =>
      handleRegion(path, 'dare'),

    '/region': (path) =>
      handleRegion(path, 'nm'),
  };


  const handleDeepLink = async (url?: string) => {
    const link = url || (await Linking.getInitialURL());
    if (link) {
      const { path } = parseURL(link);

      const entry = Object.entries(deepLinkHandlers).find(
        ([prefix]) => path.startsWith(prefix),
      );

      entry?.[1](path);
    }

    if (!initialUrlProcessed) {
      setInitialUrlProcessed(true);
    }
  };

  useEffect(() => {
    if (!initialUrlProcessed) {
      handleDeepLink();
    }

    const subscription = Linking.addEventListener('url', (event) => {
      handleDeepLink(event.url);
    });

    return () => {
      subscription.remove();
    };
  }, [initialUrlProcessed]);

  return (
    <NavigationContext.Provider value={{ handleDeepLink }}>{children}</NavigationContext.Provider>
  );
};
