import { LinkingOptions } from '@react-navigation/native'
import * as Amplitude from 'expo-analytics-amplitude'
import Constants, { AppOwnership } from 'expo-constants'
import * as Linking from 'expo-linking'
import * as Notifications from 'expo-notifications'

import { ScreenNames } from './constants/ScreenNames'
import { Mode } from './types/helpers'

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.Countries,
        screens: {
          [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.TrackStreamsGraph]:
            'artists/:artistId/tracks/:isrc/streams-graph',
          [ScreenNames.TrackCharts]: 'artists/:artistId/tracks/:isrc/charts',
          [ScreenNames.TrackTikTok]: 'artists/:artistId/tracks/:isrc/tiktok',
          [ScreenNames.TrackPlaylist]:
            'artists/:artistId/tracks/:isrc/playlists/:playlistId',
        },
      },
      [ScreenNames.ArtistTab]: {
        initialRouteName: ScreenNames.Artist,
        screens: {
          [ScreenNames.Followers]: 'artists/:artistId/followers/:dspSlug',
          [ScreenNames.Artist]: 'artists/:artistId',
        },
      },
    },
  },
  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()
    }
  },
}

const artistScreenPath = (artistId: string) => `artists/${artistId}`
export const ScreenPaths = {
  [ScreenNames.Market]: (artistId: string, countryCode: string) =>
    `${artistScreenPath(artistId)}/countries/${countryCode}`,
  [ScreenNames.Countries]: (artistId: string) =>
    `${artistScreenPath(artistId)}/countries`,
  [ScreenNames.Library]: (artistId: string) =>
    `${artistScreenPath(artistId)}/library`,
  [ScreenNames.Tracks]: (artistId: string) =>
    `${artistScreenPath(artistId)}/tracks`,
  [ScreenNames.Track]: (artistId: string, isrc: string) =>
    `${artistScreenPath(artistId)}/tracks/${isrc}`,
  [ScreenNames.TrackStreamsGraph]: (artistId: string, isrc: string) =>
    `${artistScreenPath(artistId)}/tracks/${isrc}/streams-graph`,
  [ScreenNames.TrackPlaylist]: (
    artistId: string,
    isrc: string,
    playlistId: string
  ) => `${artistScreenPath(artistId)}/tracks/${isrc}/playlists/${playlistId}`,
  [ScreenNames.TrackCharts]: (artistId: string, isrc: string) =>
    `${artistScreenPath(artistId)}/tracks/${isrc}/charts`,
  [ScreenNames.TrackTikTok]: (artistId: string, isrc: string) =>
    `${artistScreenPath(artistId)}/tracks/${isrc}/tiktok`,
  [ScreenNames.Followers]: (artistId: string, dspId: string) =>
    `${artistScreenPath(artistId)}/followers/${dspId}`,
  [ScreenNames.Artist]: artistScreenPath,
}
