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

import { Colors } from 'src/theme';

import * as MapLibreRN from '@maplibre/maplibre-react-native';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import moment from 'moment';
import { styles } from '../MarkerItem/styles';

const UserItem = ({ marker }: { marker: any }) => {
  const calloutUserRef = useRef<MapLibreRN.PointAnnotationRef>(null);
  const navigation = useNavigation();
  const [refreshKey, setRefreshKey] = useState(0);

  useFocusEffect(
    useCallback(() => {
      if (Platform.OS === 'android') {
        const timer = setTimeout(() => {
          calloutUserRef.current?.refresh();
          setRefreshKey((prev) => prev + 1);
        }, 100);

        return () => clearTimeout(timer);
      }
    }, [])
  );

  useEffect(() => {
    if (Platform.OS === 'android') {
      calloutUserRef.current?.refresh();
    }
  }, [marker]);

  const formatDateToLocalTime = (utcDate: string) => {
    const date = moment.utc(utcDate).local();
    const now = moment();

    if (now.diff(date, 'days') === 1) {
      return 'yesterday';
    }

    if (now.diff(date, 'weeks') === 1) {
      return 'last week';
    }

    return date.fromNow();
  };

  return (
    <>
      {Platform.OS === 'ios' ? (
        <MapLibreRN.PointAnnotation
          id={marker.id.toString()}
          coordinate={marker.coordinates}
          anchor={{ x: 0.5, y: 0 }}
        >
          <View style={styles.customView}>
            <View style={styles.calloutContainer}>
              <View
                style={[
                  styles.calloutImageContainer,
                  {
                    borderColor: Colors.WHITE,
                    width: 54,
                    height: 54,
                    borderRadius: 27,
                    marginTop: -43
                  }
                ]}
              >
                <Image
                  key={marker.avatar.uri}
                  source={marker.avatar}
                  style={[styles.userImage, { width: 54, height: 54, borderRadius: 27 }]}
                  resizeMode="contain"
                />
              </View>
              <View style={styles.calloutTextContainer}>
                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    gap: 8,
                    paddingHorizontal: 12
                  }}
                >
                  <Image
                    key={marker.flag.uri}
                    source={{ uri: marker.flag.uri, cache: 'force-cache' }}
                    style={styles.flag}
                    resizeMode="cover"
                  />
                  <Text style={styles.seriesName}>
                    {marker.first_name + ' ' + marker.last_name}
                  </Text>
                </View>
                <Text style={styles.markerName}>
                  Last seen: {formatDateToLocalTime(marker.last_seen)}
                </Text>
              </View>
              <TouchableOpacity
                style={[styles.calloutButton]}
                onPress={() =>
                  navigation.navigate(
                    ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: marker.id }] as never)
                  )
                }
              >
                <Text style={styles.calloutButtonText}>See profile</Text>
              </TouchableOpacity>
            </View>
          </View>
        </MapLibreRN.PointAnnotation>
      ) : (
        <MapLibreRN.PointAnnotation
          id={marker.id.toString()}
          key={refreshKey}
          coordinate={marker.coordinates}
          anchor={{ x: 0.5, y: 1.1 }}
          onSelected={() =>
            navigation.navigate(
              ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: marker.id }] as never)
            )
          }
          selected={true}
          ref={calloutUserRef}
        >
          <View style={styles.customView}>
            <View style={styles.calloutContainer}>
              <View style={styles.calloutImageContainer}>
                <Image
                  key={marker.avatar.uri}
                  source={marker.avatar}
                  style={styles.userImage}
                  resizeMode="contain"
                />
              </View>
              <View style={styles.calloutTextContainer}>
                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    gap: 8,
                    paddingHorizontal: 12
                  }}
                >
                  <Image
                    key={marker.flag.uri}
                    source={{ uri: marker.flag.uri, cache: 'force-cache' }}
                    style={styles.flag}
                    resizeMode="cover"
                  />
                  <Text style={styles.seriesName}>
                    {marker.first_name + ' ' + marker.last_name}
                  </Text>
                </View>

                <Text style={styles.markerName}>
                  Last seen: {formatDateToLocalTime(marker.last_seen)}
                </Text>
              </View>
              <TouchableOpacity
                style={[styles.calloutButton]}
                onPress={() =>
                  navigation.navigate(
                    ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: marker.id }] as never)
                  )
                }
              >
                <Text style={styles.calloutButtonText}>See profile</Text>
              </TouchableOpacity>
            </View>
          </View>
        </MapLibreRN.PointAnnotation>
      )}
    </>
  );
};

export default UserItem;
