import React, { useState } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';
import { useUsers } from '@/contexts/UserContext'; // Adjust the import path as per your project structure
import Button from '@/components/Button';
import RemarquePopup from '@/components/popUp/RemarquePopUp';
import { useAppData } from '@/contexts/AppDataContext';


const NonEndedSuiviList: React.FC = () => {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a } = useAppData();
  const { currentUser, updateCurrentUser } = useUsers(); // Assuming you have access to currentUser and update function

  const handleEndSuivi = (suiviId: number) => {
    // Find the suivi by ID and mark it as ended
    const updatedSuivi = currentUser.suivi.map((suivi) =>
      suivi.id === suiviId ? { ...suivi, ended: true } : suivi
    );

    // Update the currentUser with the updated suivi list
    updateCurrentUser({ ...currentUser, suivi: updatedSuivi });
  };

  const renderSuiviItem = ({ item }: { item: Suivi }) => (
    <View style={styles.suiviItem}>
      <Text style={styles.suiviName}>{item.name}</Text>
      <Button text='Arrêter' isSelected onPress={()=>{handleEndSuivi(item.id);setModalVisible(true);}} />
    </View>
  );

  const nonEndedSuivi = currentUser.suivi.filter((suivi) => !suivi.ended);
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Arrêter un suivi</Text>
      {nonEndedSuivi.length === 0 ? (
        <Text style={styles.noSuiviText}>Aucun suivi actif trouvé</Text>
      ) : (
        <FlatList
          data={nonEndedSuivi}
          keyExtractor={(item) => item.id.toString()}
          renderItem={renderSuiviItem}
        />
      )}
      <RemarquePopup isVisible={modalVisible} onClose={()=>{setModalVisible(false)}} skipToRemarkSection={true}/>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
    fontFamily: 'Roboto-Regular', // Apply your app's font family here
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  noSuiviText: {
    fontSize: 18,
    textAlign: 'center',
    marginTop: 50,
  },
  suiviItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  suiviName: {
    fontSize: 18,
  },
  endButton: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    backgroundColor: 'red',
    borderRadius: 5,
  },
  endButtonText: {
    color: '#fff',
    fontWeight: 'bold',
  },
});

export default NonEndedSuiviList;
