import { Dimensions, FlatList, StyleSheet, Text, View } from 'react-native'
import React, { useContext, useEffect, useRef, useState } from 'react'
import ItemList from './ItemList'
import { MarkerContext } from '@/app/context/MakerContext';
import { collection, query, where, getDocs, getFirestore } from "firebase/firestore";
import { app } from '@/app/misc/FirebaseConfig';
import { useUser } from '@clerk/clerk-expo';

const EVListView = ({placeList}) => {
  const {user} = useUser();
  const [saveList, setSaveList] = useState([]);
  const flatListRef = useRef(null);
  const {selectedMarker, setSelectedMarker} = useContext(MarkerContext);

  useEffect(() => {
    selectedMarker && scrollToIndex(selectedMarker);
  }, [selectedMarker])

  const scrollToIndex = (index) => {
    flatListRef.current?.scrollToIndex({animated: true, index})
  }

  const getItemLayout = (_,index) => ({
    length: Dimensions.get('window').width,
    offset: Dimensions.get('window').width*index,
    index
  });

  
  const db = getFirestore(app);
  useEffect(() => {
    user && getSaveList();
  }, [user])

  const getSaveList = async() => {
    setSaveList([])
    const q = query(collection(db, "ev-save"), where("email", "==", user?.primaryEmailAddress?.emailAddress));

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());
      setSaveList(saveList => [...saveList, doc.data()]);
    });
  }

  const isSave = (place) => {
    const result = saveList.find(item => item.place.id == place.id);
    return result?true : false;
  }

  return (
    <View>
      <FlatList horizontal={true}
        getItemLayout={getItemLayout}
        data={placeList} 
        showsHorizontalScrollIndicator={false} 
        ref={flatListRef}
        renderItem={({item, index}) => (
          <View key={index}>
            <ItemList place={item} isSave={isSave(item)} markedSave={() => getSaveList()}/>
          </View>
        )}
      />
    </View>
  )
}

export default EVListView

const styles = StyleSheet.create({})