import React, { createContext, useContext, useEffect, useState } from 'react';
import { Linking, Platform } from 'react-native';
import { 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 = () => {
  const context = useContext(NavigationContext);
  if (!context) {
    throw new Error('useNavigationContext must be used within a NavigationProvider');
  }
  return context;
};

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());
    console.log('Deep Link URL:', link);
    if (link) {
      const { path } = parseURL(link);
      console.log('Parsed URL:', { path });
      if (path.startsWith('/profile') && token) {
        const segments = path.split('/');
        const userId = segments[2];
        console.log('Navigating to public profile:', userId);
        navigation.navigate(...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId }] as never));
      }
    }
    if (!initialUrlProcessed) {
      setInitialUrlProcessed(true);
    }
  };

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

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

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

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