import React, { useEffect, useState, useContext } from 'react';
import { View, ScrollView, StyleSheet, Modal, TouchableOpacity, Dimensions, TextInput, KeyboardAvoidingView, Platform } from 'react-native';
import { AntDesign } from '@expo/vector-icons';
import { Antecedent, Remarque, Vaccin, User, Symptome, Pathologie } from '@/constants/type';
import Button from '@/components/Button';
import { useUsers } from '@/contexts/UserContext'; // Import UserContext
import AppText from '../AppText';
import { router } from 'expo-router';
import i18n from '@/i18n/config';

type Props = {
    isVisible: boolean;
    onClose: () => void;

};

const FrequencyPopup: React.FC<Props> = ({ isVisible, onClose }: Props) => {

    const { currentUser, updateCurrentUserAsync } = useUsers();
    const activePathologies = currentUser.suivi.filter((pathology) => !pathology.ended);
    const [suivi, setSuivi] = useState<Pathologie[]>(() => {
        const activePathologies = currentUser?.suivi?.filter((pathology) => !pathology.ended) || [];
        if (currentUser?.custom_suivi && !currentUser.custom_suivi.ended) {
          return [...activePathologies, currentUser.custom_suivi];
        }
        return activePathologies;
      });

    if (currentUser.custom_suivi && !currentUser.custom_suivi.ended) {
        activePathologies.push(currentUser.custom_suivi);
    }

    // Retrieve all symptoms from active pathologies and remove duplicates
    const allSymptoms: Symptome[] = Array.from(
        new Set(
            activePathologies.flatMap((pathology) =>
                pathology?.symptoms?.map((symptom) => ({ ...symptom, pathologyName: pathology.name })) || []
            )
        )
    );

    const [symptoms, setSymptoms] = useState<Symptome[]>(allSymptoms);

    useEffect(() => {
        setSymptoms(allSymptoms.map(symptom => ({
          ...symptom,
          frequency: symptom.frequency || 1
        })));
      }, []);

      const handleClose = async () => {
        console.log("Suivi before update:", suivi);
        console.log("Symptoms before update:", symptoms);
      
        if (!Array.isArray(suivi)) {
          console.error("Suivi is not an array:", suivi);
          onClose();
          return;
        }
      
        try {
          const updatedSuivi = suivi.map(pathology => {
            if (!pathology.symptoms || !Array.isArray(pathology.symptoms)) {
              console.error("Invalid pathology symptoms:", pathology);
              return pathology;
            }
            return {
              ...pathology,
              symptoms: pathology.symptoms.map(symptom => {
                const updatedSymptom = symptoms.find(s => s.id === symptom.id);
                return updatedSymptom ? { ...symptom, frequency: updatedSymptom.frequency } : symptom;
              })
            };
          });
      
          console.log("Updated suivi:", updatedSuivi);
      
          setSuivi(updatedSuivi);
          await updateCurrentUserAsync({ suivi: updatedSuivi });
          onClose();
        } catch (error) {
          console.error("Error in handleClose:", error);
          onClose();
        }
      };



    return (
        <Modal visible={isVisible} transparent>
            <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
                <View style={[styles.popV2, { width: Dimensions.get('window').width, height: Dimensions.get('window').height }]}>
                    {symptoms.length > 0 && symptoms.map((symptom, index) => {
                        return (
                            <View key={index} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: 10 }}>
                                <AppText text={symptom.name} />
                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    <Button
                                        text={'-'}
                                        onPress={() => {
                                            setSymptoms(prevSymptoms => prevSymptoms.map((s, i) =>
                                                i === index ? { ...s, frequency: Math.max((s.frequency || 1) - 1, 1) } : s
                                            ));
                                        }}
                                    />
                                    <AppText text={(symptom.frequency || 1).toString()} style={{ marginHorizontal: 10 }} />
                                    <Button
                                        text={'+'}
                                        onPress={() => {
                                            setSymptoms(prevSymptoms => prevSymptoms.map((s, i) =>
                                                i === index ? { ...s, frequency: (s.frequency || 1) + 1 } : s
                                            ));
                                        }}
                                    />
                                </View>
                            </View>
                        );
                    })}
                    <Button text={i18n.t('commons.validate')} onPress={handleClose} />
                </View>
            </KeyboardAvoidingView>
        </Modal>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.5)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    popV2: {
        backgroundColor: 'white',
        padding: 20,
        borderRadius: 10,
        flex: 1,
        justifyContent: 'center',
    },
    remarkItem: {
        paddingVertical: 10,
        paddingHorizontal: 20,
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 10,
        borderTopWidth: 1,
        borderColor: '#ccc',
        position: 'absolute',
        bottom: 0,
        width: '100%',
        backgroundColor: 'white',
    },
    input: {
        flex: 1,
        marginRight: 10,
        padding: 10,
    },
    backButton: {
        position: 'absolute',
        top: 10,
        left: 10,
        padding: 10,
        zIndex: 10,
    },
});

export default FrequencyPopup;
