import { LinkingOptions } from '@react-navigation/native'
import { ScreenNames } from './constants/ScreenNames'
import { Mode } from './types/helpers'
import * as Linking from 'expo-linking'
import * as Notifications from 'expo-notifications'
import * as Amplitude from 'expo-analytics-amplitude'

import Constants, { AppOwnership } from 'expo-constants'

const prefixes = [
  'https://insights.stream',
  'insights://' /* match app.config.json {expo: {scheme: string}} value */,
]

if (Constants.appOwnership === AppOwnership.Expo) {
  const prefix = Linking.createURL('/')
  prefixes.push(prefix)
  console.log('test deeplinks with\n')
  console.log('    adb shell am start -W -a android.intent.action.VIEW -d \\')
  console.log(`      ${prefix}artists/GRAS_4867/tracks?mode=${Mode.ALL}`)
  console.log('\n')
}

function logNotificationInteraction(
  event: Notifications.NotificationResponse
): void {
  Amplitude.logEventWithPropertiesAsync('notification_interaction', event)
}

export const linking: LinkingOptions = {
  prefixes,
  config: {
    screens: {
      [ScreenNames.CountriesTab]: {
        initialRouteName: ScreenNames.Globe,
        screens: {
          [ScreenNames.Globe]: 'artists/:artistId/globe',
          [ScreenNames.Market]: 'artists/:artistId/countries/:countryCode',
          [ScreenNames.Countries]: 'artists/:artistId/countries',
        },
      },
      [ScreenNames.TracksTab]: {
        initialRouteName: ScreenNames.Library,
        screens: {
          [ScreenNames.Library]: 'artists/:artistId/library',
          [ScreenNames.Tracks]: 'artists/:artistId/tracks',
          [ScreenNames.Track]: 'artists/:artistId/tracks/:isrc',
          [ScreenNames.TrackTikTok]: 'artists/:artistId/tracks/:isrc/tiktok',
        },
      },
      [ScreenNames.SocialTab]: {
        initialRouteName: ScreenNames.Social,
        screens: {
          [ScreenNames.Followers]:
            'artists/:artistId/social/followers/:dspSlug',
          [ScreenNames.Social]: 'artists/:artistId/social',
        },
      },
    },
  },
  async getInitialURL() {
    // If app was opened from a deep link, just return that
    const initialUrl = await Linking.getInitialURL()

    // Handle URL from expo push notifications for closed app
    const response = await Notifications.getLastNotificationResponseAsync()
    const notificationUrl = response?.notification.request.content.data.url as
      | string
      | undefined

    return notificationUrl ?? initialUrl ?? '/'
  },
  subscribe(listener) {
    const onReceiveURL = (event: { url: string }) => listener(event.url)

    Linking.addEventListener('url', onReceiveURL)

    const subscription = Notifications.addNotificationResponseReceivedListener(
      (response) => {
        const url = response.notification.request.content.data.url as string
        logNotificationInteraction(response)
        listener(url)
      }
    )

    return () => {
      Linking.removeEventListener('url', onReceiveURL)
      subscription.remove()
    }
  },
}
