import React, { useState, useEffect, useContext } from 'react';
import { View, FlatList, StyleSheet, Pressable } from 'react-native';
import { CheckBox } from 'react-native-elements';
import { Pathologie, Symptome } from '@/constants/type';
import AppText from '@/components/AppText';
import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import colors from '@/styles/colors';
import { filteredSuivi, parsedSymptoms } from '@/constants/constants';
import Button from '@/components/Button';
import { ImageContext } from '@/contexts/ImageContext';
import { useUsers } from '@/contexts/UserContext';
import fichier_8a from '@/assets/json/fichier_8a.json';
import pathologiesJSON from '@/assets/json/pathologie_parsed.json';
import { useNavigation, CommonActions } from '@react-navigation/native';
import { useAppData } from '@/contexts/AppDataContext';


const SymptomsAssociatedWithSuivi: React.FC = () => {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a } = useAppData();
  const { evaluateur, id_suivi } = useLocalSearchParams<{ evaluateur: string; id_suivi: any }>();
  const [checkedItems, setCheckedItems] = useState<number[]>([]);
  const router = useRouter();
  const { imageProp, setImageProp } = useContext(ImageContext);
  const { currentUser, updateCurrentUser, updateCurrentUserAsync } = useUsers();
  const filteredSuiviItem = filteredSuivi.find(item => item.id == id_suivi);
  const symptoms = filteredSuiviItem ? filteredSuiviItem.symptoms : [];
  const [pressed, setPressed] = useState<boolean>(false);

  useFocusEffect(() => {
    if (filteredSuiviItem) {
      const pathology = pathologiesJSON.find(p => p.id === filteredSuiviItem.id);
      if (pathology && pathology.logo) {
        setImageProp(pathology.logo);
      } else {
        setImageProp(undefined); // Handle the case when no logo is found
      }
    }
  });

  const handleCheckboxToggle = (id: number) => {
    setCheckedItems(prevState =>
      prevState.includes(id)
        ? prevState.filter(itemId => itemId !== id)
        : [...prevState, id]
    );
  };

  const [symptomsArray, setSymptomsArray] = useState<Symptome[]>([]);

  useEffect(() => {
    setSymptomsArray(parsedSymptoms.filter(s => checkedItems.includes(s.id)));
  }, [checkedItems]);
   // Dans le composant :
  const navigation = useNavigation<any>();

  const handleValidatePress = () => {
    if (!currentUser) return;

    const idSuiviNumber = typeof id_suivi === 'string' ? parseInt(id_suivi) : id_suivi;

    const updatedSuivi = currentUser.suivi.find(p => p.id === idSuiviNumber && !p.ended);
    const newPathArray: Pathologie = {
      name: updatedSuivi?.name ?? "",
      id: updatedSuivi?.id ?? idSuiviNumber,
      symptoms: symptomsArray,
      init_symptoms: updatedSuivi?.init_symptoms,
      evaluateur,
      date: new Date(),
      ended: false,
      icon: updatedSuivi?.icon,
      namelogo: updatedSuivi?.namelogo,
    };

    const allSuiviExcept = [
      ...currentUser.suivi.filter(p => !(p.id === idSuiviNumber && !p.ended)),
      newPathArray
    ];

    updateCurrentUserAsync({ suivi: allSuiviExcept }).then(() => {
      const pathologie = pathologiesJSON.find(p => p.id === idSuiviNumber);
      const href = fichier_8a.find(e => e.id === pathologie?.id_8a)?.href;

      // ← Réinitialise le stack du tab à son index (PathologyList) seul
      navigation.dispatch(
        CommonActions.reset({
          index: 0,
          routes: [{ name: 'index' }]
        })
      );

      // ← Puis navigue vers la destination finale
      router.replace((href ?? '/') as any);
    });
  };

  const renderItem = ({ item }: { item: Symptome }) => (
    <Pressable
      style={({ pressed }) => [
        styles.itemContainer,
        pressed && styles.pressedItem,
      ]}
      onPress={() => handleCheckboxToggle(item.id)}
    >
      <CheckBox
        checked={checkedItems.includes(item.id)}
        onPress={() => handleCheckboxToggle(item.id)}
        checkedColor='#e8397b'
      />
      <View style={styles.itemTitleContainer}>
        <AppText style={styles.itemTitle} text={item.name} />
      </View>
    </Pressable>
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={symptoms}
        renderItem={renderItem}
        keyExtractor={(item) => item.id.toString()}
        style={styles.list}
      />
      <View style={styles.buttonContainer}>
        <Button
          text="Valider"
          onPress={handleValidatePress}
          isSelected
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 10,
  },
  list: {
    flex: 1,
  },
  buttonContainer: {
    paddingVertical: 10,
  },
  itemContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 16,
    paddingHorizontal: 24,
    backgroundColor: '#ffffff',
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
    marginTop: 10,
    marginHorizontal: 5,
    borderRadius: 5,
  },
  pressedItem: {
    backgroundColor: '#e0e0e0', // Light grey background when pressed
  },
  itemTitleContainer: {
    flex: 1,
  },
  itemTitle: {
    fontSize: 16,
    color: '#000000',
  },
});

export default SymptomsAssociatedWithSuivi;
