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);

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

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

    if (link) {
      const { path } = parseURL(link);
      if (path.startsWith('/profile') && token) {
        const segments = path.split('/');
        const userId = segments[2];
        navigation.navigate(...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId }] as never));
      } else if (path.startsWith('/event')) {
        const segments = path.split('/');
        const eventUrl = segments[2];

        navigation.dispatch(
          CommonActions.reset({
            index: 1,
            routes: [
              {
                name: 'DrawerApp',
                state: {
                  routes: [
                    {
                      name: NAVIGATION_PAGES.IN_APP_TRAVELS_TAB,
                      state: {
                        routes: [
                          { name: NAVIGATION_PAGES.EVENTS },
                          {
                            name: NAVIGATION_PAGES.EVENT,
                            params: { url: eventUrl }
                          }
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          })
        );
      }
    }
    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>
  );
};
