import { Platform, TouchableOpacity, View, Image, Text } from 'react-native';
import React, { FC, useEffect, useRef, useState } from 'react';
import MapView, { UrlTile } from 'react-native-maps';

import { styles } from './styles';
import { API_HOST, FASTEST_MAP_HOST } from 'src/constants';
import { NavigationProp } from '@react-navigation/native';
import { AvatarWithInitials } from 'src/components';
import { Colors } from 'src/theme';

import CloseSvg from 'assets/icons/close.svg';
import FilterIcon from 'assets/icons/filter.svg';
import FilterModal from '../../MapScreen/FilterModal';

type Props = {
  navigation: NavigationProp<any>;
  route: any;
};

const UsersMapScreen: FC<Props> = ({ navigation, route }) => {
  const userId = route.params?.userId;
  const data = route.params?.data;

  const tilesBaseURL = `${FASTEST_MAP_HOST}/tiles_osm`;
  const gridUrl = `${FASTEST_MAP_HOST}/tiles_nm/grid`;
  const visitedTiles = `${FASTEST_MAP_HOST}/tiles_nm/user_visited/${userId}`;
  const visitedUNTiles = `${FASTEST_MAP_HOST}/tiles_nm/user_visited_un/${userId}`;

  const mapRef = useRef<MapView>(null);
  const [isFilterVisible, setIsFilterVisible] = useState(false);
  const [tilesType, setTilesType] = useState({ label: 'NM regions', value: 0 });
  const tilesTypes = [
    { label: 'NM regions', value: 0 },
    { label: 'UN countries', value: 1 }
  ];
  const [type, setType] = useState(0);

  useEffect(() => {
    navigation.getParent()?.setOptions({
      tabBarStyle: {
        display: 'none',
        position: 'absolute',
        ...Platform.select({
          android: {
            height: 58
          }
        })
      }
    });
  }, [navigation]);

  const renderMapTiles = (url: string, zIndex: number, opacity = 1) => (
    <UrlTile
      key={url}
      urlTemplate={`${url}/{z}/{x}/{y}`}
      maximumZ={15}
      maximumNativeZ={13}
      shouldReplaceMapContent
      minimumZ={0}
      opacity={opacity}
      zIndex={zIndex}
    />
  );

  const handleGoBack = () => {
    navigation.getParent()?.setOptions({
      tabBarStyle: {
        display: 'flex',
        position: 'absolute',
        ...Platform.select({
          android: {
            height: 58
          }
        })
      }
    });
    navigation.goBack();
  };

  return (
    <View style={styles.container}>
      <MapView
        initialRegion={{
          latitude: 0,
          longitude: 0,
          latitudeDelta: 180,
          longitudeDelta: 180
        }}
        ref={mapRef}
        showsMyLocationButton={false}
        showsCompass={false}
        zoomControlEnabled={false}
        style={styles.map}
        mapType={Platform.OS == 'android' ? 'none' : 'standard'}
        maxZoomLevel={15}
        minZoomLevel={0}
      >
        {renderMapTiles(tilesBaseURL, 1)}
        {renderMapTiles(gridUrl, 2)}
        {userId && renderMapTiles(type === 1 ? visitedUNTiles : visitedTiles, 2, 0.5)}
      </MapView>

      <TouchableOpacity
        style={[styles.cornerButton, styles.topLeftButton, styles.closeLeftButton]}
        onPress={handleGoBack}
      >
        <CloseSvg fill="white" width={13} height={13} />
        <Text style={styles.textClose}>Close</Text>
      </TouchableOpacity>
      <View style={[styles.cornerButton, styles.topRightButton]}>
        {data.avatar ? (
          <Image style={styles.avatar} source={{ uri: API_HOST + data.avatar }} />
        ) : (
          <AvatarWithInitials
            text={`${data.first_name[0] ?? ''}${data.last_name[0] ?? ''}`}
            flag={API_HOST + data.homebase_flag}
            size={48}
            borderColor={Colors.WHITE}
          />
        )}
      </View>
      <TouchableOpacity
        style={[styles.cornerButton, styles.bottomButton, styles.bottomLeftButton]}
        onPress={() => setIsFilterVisible(true)}
      >
        <FilterIcon />
      </TouchableOpacity>
      <FilterModal
        isFilterVisible={isFilterVisible}
        setIsFilterVisible={setIsFilterVisible}
        tilesTypes={tilesTypes}
        tilesType={tilesType}
        setTilesType={setTilesType}
        type={type}
        setType={setType}
      />
    </View>
  );
};

export default UsersMapScreen;
