import { useEffect, useRef } from 'react';
import { View, Image, Text, TouchableOpacity, Platform } from 'react-native';

import { styles } from './styles';
import { Colors } from 'src/theme';

import CheckSvg from 'assets/icons/mark.svg';
import * as MapLibreRN from '@maplibre/maplibre-react-native';
import { API_HOST } from 'src/constants';
import { NAVIGATION_PAGES } from 'src/types';
import { useNavigation } from '@react-navigation/native';

const MarkerItem = ({
  marker,
  toggleSeries,
  token,
  isPremium,
  setPremiumModalVisible
}: {
  marker: any;
  toggleSeries: (item: any) => void;
  token: string;
  isPremium: boolean;
  setPremiumModalVisible: (premium: boolean) => void;
}) => {
  const navigation = useNavigation();

  function formatNumber(value?: number | null) {
    const number = typeof value === 'number' && !isNaN(value) ? value : 0;

    if (number >= 1000 && number < 10000) {
      return (number / 1000).toFixed(1) + 'k';
    } else if (number >= 10000) {
      return (number / 1000).toFixed(0) + 'k';
    }

    return number.toString();
  }
  const formattedCount = formatNumber(marker.no_visited);
  const parsedAvatars =
    typeof marker.avatars === 'string' ? JSON.parse(marker.avatars) : marker.avatars;

  return (
    <>
      {Platform.OS === 'ios' ? (
        <MapLibreRN.PointAnnotation
          id="selected_marker_callout"
          coordinate={marker.coordinates}
          anchor={{ x: 0.5, y: 1 }}
        >
          <View style={styles.customView}>
            <View style={styles.calloutContainer}>
              <View style={styles.calloutImageContainer}>
                <Image
                  source={{ uri: marker.icon?.uri || '' }}
                  style={styles.calloutImage}
                  resizeMode="contain"
                />
              </View>
              <View style={styles.calloutTextContainer}>
                <Text style={styles.seriesName}>{marker.series_name}</Text>
                <Text style={styles.markerName} selectable={true}>
                  {marker.name}
                </Text>
              </View>

              <TouchableOpacity
                style={[
                  styles.calloutButton,
                  (marker.visited === 1 &&
                    token && {
                      backgroundColor: Colors.WHITE,
                      borderWidth: 1,
                      borderColor: Colors.BORDER_LIGHT
                    }) ||
                    {}
                ]}
                onPress={() => toggleSeries(marker)}
              >
                <View style={styles.completedContainer}>
                  <View style={{ display: marker?.visited === 1 && token ? 'flex' : 'none' }}>
                    <CheckSvg width={14} height={14} fill={Colors.DARK_BLUE} />
                  </View>
                  <Text
                    style={[
                      styles.calloutButtonText,
                      marker?.visited === 1 && token ? { color: Colors.DARK_BLUE } : {}
                    ]}
                  >
                    {marker?.visited === 1 && token ? 'Completed' : 'To Complete'}
                  </Text>
                </View>
              </TouchableOpacity>

              {parsedAvatars && (
                <TouchableOpacity
                  onPress={() => {
                    if (!isPremium) {
                      setPremiumModalVisible(true);
                    } else {
                      navigation.navigate(
                        ...([
                          NAVIGATION_PAGES.USERS_LIST,
                          {
                            id: marker.id,
                            isFromHere: false,
                            type: 'series'
                          }
                        ] as never)
                      );
                    }
                  }}
                  style={styles.userImageContainer}
                >
                  {parsedAvatars?.map((avatar: number, index: number) => (
                    <Image
                      key={avatar}
                      source={{ uri: API_HOST + '/img/avatars/' + avatar + '.webp' }}
                      style={styles.userImageSmall}
                    />
                  ))}
                  <View style={styles.userCountContainer}>
                    <Text style={styles.userCount}>{formattedCount}</Text>
                  </View>
                </TouchableOpacity>
              )}
            </View>
          </View>
        </MapLibreRN.PointAnnotation>
      ) : (
        <MapLibreRN.MarkerView
          key={`${marker.id}-${marker.visited}`}
          id="selected_marker_callout"
          coordinate={marker.coordinates}
          anchor={{ x: 0.5, y: 0.9 }}
        >
          <View style={styles.customView}>
            <View style={styles.calloutContainer}>
              <View style={styles.calloutImageContainer}>
                <Image
                  source={{ uri: marker.icon?.uri || '' }}
                  style={styles.calloutImage}
                  resizeMode="contain"
                />
              </View>
              <View style={[styles.calloutTextContainer, { flex: 0 }]}>
                <Text style={styles.seriesName}>{marker.series_name}</Text>
                <Text style={styles.markerName} selectable={true}>
                  {marker.name}
                </Text>
              </View>

              <TouchableOpacity
                style={[
                  styles.calloutButton,
                  (marker.visited === 1 &&
                    token && {
                      backgroundColor: Colors.WHITE,
                      borderWidth: 1,
                      borderColor: Colors.BORDER_LIGHT
                    }) ||
                    {}
                ]}
                onPressIn={() => toggleSeries(marker)}
              >
                <View style={styles.completedContainer}>
                  <View style={{ display: marker?.visited === 1 && token ? 'flex' : 'none' }}>
                    <CheckSvg width={14} height={14} fill={Colors.DARK_BLUE} />
                  </View>
                  <Text
                    style={[
                      styles.calloutButtonText,
                      marker?.visited === 1 && token ? { color: Colors.DARK_BLUE } : {}
                    ]}
                  >
                    {marker?.visited === 1 && token ? 'Completed' : 'To Complete'}
                  </Text>
                </View>
              </TouchableOpacity>

              {parsedAvatars && (
                <TouchableOpacity
                  onPressIn={() => {
                    if (!isPremium) {
                      setPremiumModalVisible(true);
                    } else {
                      navigation.navigate(
                        ...([
                          NAVIGATION_PAGES.USERS_LIST,
                          {
                            id: marker.id,
                            isFromHere: false,
                            type: 'series'
                          }
                        ] as never)
                      );
                    }
                  }}
                  style={styles.userImageContainer}
                >
                  {parsedAvatars?.map((avatar: number, index: number) => (
                    <Image
                      key={avatar}
                      source={{ uri: API_HOST + '/img/avatars/' + avatar + '.webp' }}
                      style={styles.userImageSmall}
                    />
                  ))}
                  <View style={styles.userCountContainer}>
                    <Text style={styles.userCount}>{formattedCount}</Text>
                  </View>
                </TouchableOpacity>
              )}
            </View>
          </View>
        </MapLibreRN.MarkerView>
      )}
    </>
  );
};

export default MarkerItem;
