import MapView from "react-native-maps";
import { View } from "react-native";
import { router, useFocusEffect } from "expo-router";
import { CustomMapMarker } from "../components/maps/custom_map_marker";
import { useGetRouteActivities } from "../hooks/useGetRouteActivities";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { FullPageLoader } from "../../common/components/full_page_loader";
import { useRef } from "react";
import { ActivityRouteEntity } from "../../activity/domain/entities/activity_info_entity";

interface MapsPageProps {
  routeId: number;
}

export const MapsPage = ({ routeId }: MapsPageProps) => {
  const {
    activities: routeActivities,
    requestStatus,
    refresh,
  } = useGetRouteActivities(routeId);
  const reloadIsNeededRef = useRef(false);

  useFocusEffect(() => {
    if (reloadIsNeededRef.current) {
      refresh();
      reloadIsNeededRef.current = false;
    }
  });

  if (requestStatus === ApiRequestStatus.LOADING) {
    return <FullPageLoader />;
  }

  if (requestStatus === ApiRequestStatus.ERROR || !routeActivities) {
    return <View />;
  }

  return (
    <View style={{ flex: 1 }}>
      <MapView
        style={{ flex: 1 }}
        initialRegion={{
          latitude: routeActivities[0].coordinates.latitude,
          longitude: routeActivities[0].coordinates.longitude,
          latitudeDelta: 1,
          longitudeDelta: 1,
        }}
      >
        {routeActivities.map((activity: ActivityRouteEntity) => (
          <CustomMapMarker
            key={activity.id}
            isFinished={activity.done}
            title={activity.name}
            imageUri={activity.imageUri}
            coordinate={{
              latitude: activity.coordinates.latitude,
              longitude: activity.coordinates.longitude,
            }}
            onPress={() => {
              reloadIsNeededRef.current = true;
              router.push("scan");
            }}
          />
        ))}
      </MapView>
    </View>
  );
};
