import React, {memo, useCallback, useEffect, useRef, useState} from 'react';
import {View, StyleSheet} from 'react-native';
import {useTranslation} from 'react-i18next';
import MapView, {Marker, Circle} from 'react-native-maps';
import {Alert, CardContainer} from '@components';
import {SiteResponse} from '@modules/timeTracking/interfaces';
import {TIME_TRACKING_REMOTE_SITE_OPTION_ID} from '@modules/timeTracking/constants';
import {useAppSelector} from '@redux/utils';
import {ICON_SIZES, SPACING, useTheme} from '@shared/theme';
import {hexToRgb} from '@shared/colors';

import SpotlightMarker from './assets/spotlightMarker.svg';
import SpotlightMarkerGray from './assets/spotlightMarkerGray.svg';
import {styles} from './styles';

interface Props {
  fullSelectedSite?: SiteResponse;
  isInsideSite: boolean;
  isSitesEmpty: boolean;
}

const CENTER_OFFSET = {x: 0, y: -20};
const PADDING = SPACING.x5;
const MARKER_SIZE = ICON_SIZES.x11;
const MAX_ZOOM_LEVEL = 16;

function Map({fullSelectedSite, isInsideSite, isSitesEmpty}: Props) {
  const {theme} = useTheme();
  const {t} = useTranslation();
  const [loadingMap, setIsLoadingMap] = useState(true);
  const mapRef = useRef<Nullable<MapView>>(null);
  const currentPosition = useAppSelector(
    ({timeTracking}) => timeTracking.position,
  );
  const locations = useAppSelector(({timeTracking}) => timeTracking.locations);
  const hasGeoFencing = useAppSelector(
    ({timeTracking}) => timeTracking.policies?.geofencing,
  );
  const hasGeoFencingError = hasGeoFencing && !isSitesEmpty && !isInsideSite;
  const circleColor = hexToRgb(theme.graphics.hugo[500], 0.3);

  useEffect(() => {
    if (currentPosition && !loadingMap) {
      mapRef.current?.fitToCoordinates(
        fullSelectedSite
          ? [currentPosition.coords, fullSelectedSite.location]
          : [currentPosition.coords],
        {
          edgePadding: {
            top: PADDING,
            bottom: PADDING,
            left: PADDING,
            right: PADDING,
          },
        },
      );
    }
  }, [currentPosition, fullSelectedSite, loadingMap]);

  const onMapReady = () => {
    setIsLoadingMap(false);
  };

  const renderMarker = useCallback(
    (location: SiteResponse) => {
      const isSelected = location.id === fullSelectedSite?.id;
      const MarkerIcon = isSelected ? SpotlightMarker : SpotlightMarkerGray;
      return (
        <Marker
          key={`${location.id}`}
          coordinate={location.location}
          centerOffset={CENTER_OFFSET}
          title={location.name}
          tracksViewChanges={false}
          description={location?.location.address || undefined}>
          <MarkerIcon height={MARKER_SIZE} width={MARKER_SIZE} />
        </Marker>
      );
    },
    [fullSelectedSite],
  );

  return (
    <View style={styles.mapContainer}>
      {hasGeoFencingError && (
        <Alert title={t('time_tracker.geo_fencing_error')} variant="error" />
      )}
      {currentPosition?.coords && (
        <CardContainer
          style={styles.container}
          {...(fullSelectedSite?.id !== TIME_TRACKING_REMOTE_SITE_OPTION_ID && {
            badge: {
              hasIcon: true,
              variant: isSitesEmpty
                ? 'info'
                : isInsideSite
                ? 'success'
                : 'error',
              text: t(
                isSitesEmpty
                  ? 'time_tracker.no_locations_info'
                  : isInsideSite
                  ? 'time_tracker.inside_location'
                  : 'time_tracker.outside_location',
              ),
            },
          })}>
          <View style={styles.content}>
            <MapView
              onMapReady={onMapReady}
              ref={mapRef}
              maxZoomLevel={MAX_ZOOM_LEVEL}
              style={StyleSheet.absoluteFill}>
              {locations.map(renderMarker)}
              <Marker
                tracksViewChanges={false}
                coordinate={currentPosition.coords}>
                <View
                  style={[
                    styles.userMarker,
                    {
                      backgroundColor: theme.graphics.hugo[500],
                      borderColor: theme.background.layout.tertiary,
                    },
                  ]}
                />
              </Marker>
              {fullSelectedSite &&
                fullSelectedSite.id !== TIME_TRACKING_REMOTE_SITE_OPTION_ID && (
                  <Circle
                    center={fullSelectedSite.location}
                    radius={fullSelectedSite.location.tolerance}
                    zIndex={1}
                    strokeColor={circleColor}
                    fillColor={circleColor}
                  />
                )}
            </MapView>
          </View>
        </CardContainer>
      )}
    </View>
  );
}

export default memo(Map);
