import { FontAwesome5, MaterialIcons } from '@expo/vector-icons'
import MapLibreGL, { Camera, FillLayer, LineLayer, MapView, PointAnnotation, RasterLayer, RasterSource, ShapeSource, UserLocation, UserTrackingMode } from '@maplibre/maplibre-react-native'
import { useQuery } from '@tanstack/react-query'
import { circle } from '@turf/circle'
import { reverseGeocodeAsync } from 'expo-location'
import React, { useEffect, useMemo, useState } from 'react'
import { StyleSheet } from 'react-native'
import { Button, Dialog, FAB, Portal, Text } from 'react-native-paper'
import { useAuth } from '@/hooks/useAuth'
import { useGame } from '@/hooks/useGame'
import { useLastOwnLocation, useLastPlayerLocations } from '@/hooks/useLocation'
import { isAuthValid } from '@/utils/features/auth/authSlice'
import { Player } from '@/utils/features/game/gameSlice'
import { PlayerLocation } from '@/utils/features/location/locationSlice'

export default function Map() {
  const [followUser, setFollowUser] = useState(true)

  return (
    <>
      <MapWrapper followUser={followUser} setFollowUser={setFollowUser} />
      <FollowUserButton key={'follow-userr-btn-component'} followUser={followUser} setFollowUser={setFollowUser} />
    </>
  )
}

type FollowUserProps = {
  followUser: boolean,
  setFollowUser: React.Dispatch<React.SetStateAction<boolean>>,
}

function MapWrapper({ followUser, setFollowUser }: FollowUserProps) {
  const [displayedPlayerId, setDisplayedPlayerId] = useState<number | null>(null)
  return (
    <>
      <MapComponent followUser={followUser} setFollowUser={setFollowUser} setDisplayedPlayerId={setDisplayedPlayerId} />
      <Portal>
        <PlayerLocationDialog displayedPlayerId={displayedPlayerId} onDismiss={() => setDisplayedPlayerId(null)} />
      </Portal>
    </>
  )
}

type MapComponentProps = {
  followUser?: boolean,
  setFollowUser: React.Dispatch<React.SetStateAction<boolean>>,
  setDisplayedPlayerId: React.Dispatch<React.SetStateAction<number | null>>
}

function MapComponent({ followUser, setFollowUser, setDisplayedPlayerId }: MapComponentProps) {
  MapLibreGL.setAccessToken(null)
  const userLocation = useLastOwnLocation()
  return (
    <MapView
      logoEnabled={false}
      compassViewPosition={2}
      style={styles.map}
      styleURL="https://openmaptiles.geo.data.gouv.fr/styles/osm-bright/style.json">
      {userLocation && <Camera
          defaultSettings={{centerCoordinate: [userLocation?.coords.longitude, userLocation?.coords.latitude], zoomLevel: 15}}
          followUserLocation={followUser}
          followUserMode={UserTrackingMode.Follow}
          followZoomLevel={16}
          onUserTrackingModeChange={(event) => {
            if (followUser && !event.nativeEvent.payload.followUserLocation)
              setFollowUser(false)
          }} />}
      
      <RasterSource id="railwaymap-source" tileUrlTemplates={["https://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png"]}></RasterSource>
      <RasterLayer id="railwaymap-layer" sourceID="railwaymap-source" style={{rasterOpacity: 0.7}} />

      <UserLocation animated={true} renderMode="native" androidRenderMode="compass" showsUserHeadingIndicator={true} />
      <PlayerLocationsMarkers setDisplayedPlayerId={setDisplayedPlayerId} />
    </MapView>
  )
}


function PlayerLocationsMarkers({ setDisplayedPlayerId }: { setDisplayedPlayerId: React.Dispatch<React.SetStateAction<number | null>> }) {
  const game = useGame()
  const lastPlayerLocations = useLastPlayerLocations()
  return lastPlayerLocations ? lastPlayerLocations
    .filter(() => !game.currentRunner || !game.gameStarted)
    .filter(playerLoc => playerLoc.playerId !== game.playerId)
    .map(playerLoc => <PlayerLocationMarker key={`player-${playerLoc.playerId}-loc`} playerLocation={playerLoc} setDisplayedPlayerId={setDisplayedPlayerId} />) : <></>
}

function PlayerLocationMarker({ playerLocation, setDisplayedPlayerId }: { playerLocation: PlayerLocation, setDisplayedPlayerId: React.Dispatch<React.SetStateAction<number | null>> }) {
  const accuracyCircle = useMemo(() => circle([playerLocation.longitude, playerLocation.latitude], playerLocation.accuracy, {steps: 64, units: 'meters'}), [playerLocation])
  return <>
    <ShapeSource
        id={`accuracy-radius-${playerLocation.playerId}`}
        shape={accuracyCircle} />
    <FillLayer
        id={`accuracy-radius-fill-${playerLocation.playerId}`}
        sourceID={`accuracy-radius-${playerLocation.playerId}`}
        style={{fillOpacity: 0.4, fillColor: 'pink'}}
        aboveLayerID="railwaymap-layer" />
    <LineLayer
        id={`accuracy-radius-border-${playerLocation.playerId}`}
        sourceID={`accuracy-radius-${playerLocation.playerId}`}
        style={{lineOpacity: 0.4, lineColor: 'red'}}
        aboveLayerID={`accuracy-radius-fill-${playerLocation.playerId}`} />
    <PointAnnotation id={`player-location-marker-${playerLocation.playerId}`}
        coordinate={[playerLocation.longitude, playerLocation.latitude]}
        onSelected={() => { setDisplayedPlayerId(playerLocation.playerId) }}>
      <FontAwesome5 name="map-marker-alt" size={24} color="red" />
    </PointAnnotation>
  </>
}

const styles = StyleSheet.create({
  map: {
    flex: 1,
    alignSelf: 'stretch',
  }
})

function FollowUserButton({ followUser, setFollowUser }: FollowUserProps) {
  return (
    <FAB
      key={'follow-user-btn'}
      style={{ position: 'absolute', right: 25, bottom: 25 }}
      icon={(props) => <MaterialIcons name={followUser ? 'my-location' : 'location-searching'} {...props} />}
      onPress={() => setFollowUser(followUser => !followUser)} />
  )
}

function PlayerLocationDialog({ displayedPlayerId, onDismiss }: { displayedPlayerId: number | null, onDismiss: () => void }) {
  const auth = useAuth()
  const lastPlayerLocations = useLastPlayerLocations()
  const playersQuery = useQuery({
      queryKey: ['get-players', auth.token],
      queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/players/`, {
        headers: { "Authorization": `Bearer ${auth.token}` }}
      ).then(resp => resp.json()),
      enabled: isAuthValid(auth),
      initialData: { data: [], meta: { currentPage: 0, lastPage: 0, nextPage: 0, prevPage: 0, total: 0, totalPerPage: 0 } },
    })

  const displayedPlayerLoc = useMemo(() => {
    return lastPlayerLocations.find(loc => loc.playerId === displayedPlayerId)
  }, [displayedPlayerId, lastPlayerLocations])

  const displayedPlayerName = useMemo(() => {
    if (!playersQuery.isSuccess || !displayedPlayerId)
      return "Chargement…"
    const player: Player | undefined = playersQuery.data.data.find((player: Player) => player.id === displayedPlayerId)
    if (!player)
      return "Chargement…"
    return player.name
  }, [displayedPlayerId, playersQuery])

  const [address, setAddress] = useState("Adresse inconnue")
  useEffect(() => {
    if (!displayedPlayerLoc)
      return setAddress("Adresse inconnue")
    reverseGeocodeAsync(displayedPlayerLoc).then(addresses => setAddress(addresses[0].formattedAddress ?? "Adresse inconnue"))
  }, [displayedPlayerLoc])

  return (
    <Dialog visible={displayedPlayerId !== null} onDismiss={onDismiss}>
      <Dialog.Title>{displayedPlayerName}</Dialog.Title>
      <Dialog.Content>
        <Text>
          Dernière position : {new Date(displayedPlayerLoc?.timestamp ?? 0).toLocaleString()}
        </Text>
        <Text>
          Précision : {displayedPlayerLoc?.accuracy.toPrecision(3)} m
        </Text>
        <Text>
          Adresse estimée : {address}
        </Text>
      </Dialog.Content>
      <Dialog.Actions>
        <Button onPress={onDismiss}>
          Fermer
        </Button>
      </Dialog.Actions>
    </Dialog>
  )
}
