import React, { useEffect } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { setEvents, toggleFavorite } from '../store/eventsSlice';
import { RootState } from '../store/store';

export default function EventsScreen({ navigation }: any) {
  const dispatch = useDispatch();
  const { events, favorites } = useSelector((state: RootState) => state.events);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(res => res.json())
      .then(data => {
        const mappedEvents = data.slice(0, 20).map((item: any) => ({
          id: item.id.toString(),
          name: item.title,
          description: item.body,
          date: new Date().toISOString(),
        }));
        dispatch(setEvents(mappedEvents));
      });
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        data={events}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={styles.item}
            onPress={() => navigation.navigate('Details', { event: item })}
          >
            <Text style={styles.title}>{item.name}</Text>
            <TouchableOpacity
              onPress={() => dispatch(toggleFavorite(item.id))}
              style={styles.favBtn}
            >
              <Text>{favorites.includes(item.id) ? '❤️' : '🤍'}</Text>
            </TouchableOpacity>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: '#000000' },
  item: { padding: 16, borderBottomWidth: 1, borderBottomColor: '#333333', flexDirection: 'row', justifyContent: 'space-between' },
  title: { fontSize: 16, flex: 1, color: '#ffffff' },
  favBtn: { padding: 8 },
});
