import React, { memo, useRef } from 'react';
import { StyleSheet, View } from 'react-native';
import MapView, { Marker, Region } from 'react-native-maps';
import Loader from '../../../shared/components/ui/Loader';
import { colors } from '../../../theme';
import MapInfoCard from '../components/MapInfoCard';
import useMapData from '../hooks/useMapData';

const MapScreen = () => {
  const mapRef = useRef<MapView>(null);

  const { currentLocation, selected, setSelected, loading, locations } = useMapData();

  const defaultRegion: Region = {
    latitude: currentLocation?.latitude || 31.6295,
    longitude: currentLocation?.longitude || -8.0083,
    latitudeDelta: 0.2,
    longitudeDelta: 0.2,
  };

  if (loading) {
    return <Loader />;
  }

  return (
    <View style={styles.container}>
      <MapView
        ref={mapRef}
        style={styles.map}
        initialRegion={defaultRegion}
        showsUserLocation
      >
        {locations.map((location) => (
          <Marker
            key={location.id}
            coordinate={location.coordinate}
            pinColor={location.hasExist ? colors.gray400 : colors.primary}
            onPress={() => setSelected(location)}
          />
        ))}
      </MapView>

      {selected && <MapInfoCard location={selected} unit={'km'} />}
    </View>
  );
};

export default memo(MapScreen);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.white,
  },
  map: {
    flex: 1,
  },
});