// MapScreen.tsx
import { ThemedMapView } from '@/components/theme/themed-mapview';
import { ThemedText } from '@/components/theme/themed-text';
import { ThemedButton } from '@/components/theme/themed-button';
import React, { useEffect, useState } from 'react';
import { StyleSheet, View, Dimensions, Image, Text } from 'react-native';
import MapView, { Marker, Callout, CalloutSubview, PROVIDER_DEFAULT } from 'react-native-maps';
import { db } from '../../firebase_config';
import { Chantier } from '@/class/class';
import { getChantiers } from '@/services/ressourcesService';
import { useLocation } from '@/hooks/useLocation';



const MapScreen = () => {

const region = {
    latitude: 48.8566,
    longitude: 2.3522,
    latitudeDelta: 0.05,
    longitudeDelta: 0.05,
  };


  const [chantiers, setMarkers] = useState<Chantier[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);


      async function loadData() {
      try {
        setRefreshing(true)
        const data = await getChantiers();
        console.log("Chantiers chargés:", data.length);
        console.log("📍 Premier chantier:", data[-1]);
        console.log("🗺️ Coordonnées:", data[-1]?.latitude, data[-1]?.longitude);
        setMarkers(data);
      } catch (error) {
        console.error("Erreur lors du chargement :", error);
      } finally {
        setLoading(false);
        setRefreshing(false);
      }
    }
 useEffect(() => {
    loadData();
  }, []);

  console.log("🔄 Render - Nombre de chantiers:", chantiers.length);

  return (
    <View style={styles.container}>
      <ThemedMapView
        provider={PROVIDER_DEFAULT} // OpenStreetMap
        style={styles.map}
        region={region}
      >
        {Array.isArray(chantiers) &&
        chantiers.map(chantier => (
          
          <Marker
            key = {chantier.id}
            coordinate={{ latitude: chantier.latitude, longitude: chantier.longitude}}
            title={chantier.name}
            description={chantier.etat}
          />
        ))}
      </ThemedMapView>
        <ThemedButton
          lvl={1}
          shadow={true}
          style={styles.refreshButton}
          onPress={() => loadData()}
          disabled={refreshing}
          >
          <ThemedText>Actualiser</ThemedText>
          </ThemedButton>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
  refreshButton: {
    position: 'absolute',
    top: 50,
    right: 20,
    padding: 15,
    borderRadius: 8,
  },
});

export default MapScreen;
