import React, { useEffect, useState } from 'react';
import { View, StyleSheet, Modal } from 'react-native';
import { useRouter } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import Button from '@/components/Button';
import AppText from '@/components/AppText';
import i18n from '@/i18n/config';
import { supplementary_data_result } from '@/constants/constants';
import { Symptome } from '@/constants/type';
import fonts from '@/styles/fonts';
import { useUsers } from '@/contexts/UserContext';
import { InputBox } from '../AssessSymptom';
import { ScrollView } from 'react-native-gesture-handler';

type ModalProps = {
  visible: boolean;
  onClose: () => void;
};

export default function ModifySupplementaryDataPopUp({ visible, onClose }: ModalProps) {
  const { currentUser, updateCurrentUserAsync } = useUsers();

  // 🔥 Toujours un tableau, jamais undefined
  const [textInputValues, setTextInputValues] = useState<Symptome[]>(
    Array.isArray(currentUser?.supplementary_data)
      ? currentUser.supplementary_data
      : []
  );

  // 🔥 Quand currentUser change → on recharge proprement
  useEffect(() => {
    if (Array.isArray(currentUser?.supplementary_data)) {
      setTextInputValues(currentUser.supplementary_data);
    } else {
      setTextInputValues([]); // sécurité
    }
  }, [currentUser]);

  // 🔥 Mise à jour d’un champ
  const handleTextInputChange = (id: number, value: string | number) => {
    setTextInputValues(prevValues => {
      const safePrev = Array.isArray(prevValues) ? prevValues : [];

      const updatedValues = safePrev.map(symptom =>
        symptom.id === id
          ? { ...symptom, data: [{ date: new Date(), valeur: value }] }
          : symptom
      );

      const exists = updatedValues.find(s => s.id === id);

      if (!exists) {
        const newSymptom = supplementary_data_result.find(s => s.id === id);
        if (newSymptom) {
          updatedValues.push({
            ...newSymptom,
            data: [{ date: new Date(), valeur: value }]
          });
        }
      }

      return updatedValues;
    });
  };

  const handleSliderChange = (value: number, id: number) =>
    handleTextInputChange(id, value);

  const handleTxtChange = (value: string, id: number) =>
    handleTextInputChange(id, value);

  const handleYesNoChange = (value: boolean, id: number) =>
    handleTextInputChange(id, value ? 1 : 0);

  // 🔥 Validation
  const handleLogin = async () => {
    await updateCurrentUserAsync({ supplementary_data: textInputValues });
    onClose();
  };

  // 🔥 Fonction utilitaire pour éviter les crashs
  const safeFind = (id: number) => {
    if (!Array.isArray(textInputValues)) return undefined;
    return textInputValues.find(s => s.id === id);
  };

  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={visible}
      onRequestClose={onClose}
    >
      <View style={styles.modalContainer}>
        <View style={styles.modalContent}>
          <AppText
            text={i18n.t('login.supplementary_data.title_short')}
            style={styles.title}
          />

          <ScrollView>
            {supplementary_data_result.map(symptom => {
              const found = safeFind(symptom.id);
              const lastValue = found?.data?.at(-1)?.valeur;

              return (
                <View
                  key={symptom.id}
                  style={{ flexDirection: 'column', justifyContent: 'center', padding: 20 }}
                >
                  <AppText
                    style={{ textAlign: 'center' }}
                    text={symptom.surname ? symptom.surname.toString() : symptom.name}
                  />

                  <InputBox
                    s={symptom}
                    onClose={() => {}}
                    noText
                    initsetSliderValue={
                      symptom.type === 'Num.' ? Number(lastValue) : undefined
                    }
                    initsetTexteValue={
                      symptom.type === 'Texte' ? String(lastValue ?? '') : ''
                    }
                    initsetBooleanValue={
                      symptom.type.toLowerCase().includes('oui/non')
                        ? lastValue === undefined
                          ? undefined
                          : Number(lastValue) > 0
                        : undefined
                    }
                    recupSliderValue={value => handleSliderChange(value, symptom.id)}
                    recupYesNo={value => handleYesNoChange(value, symptom.id)}
                    recupText={value => handleTxtChange(value, symptom.id)}
                    donotdispVButtons
                    ouinonSameLine
                  />
                </View>
              );
            })}

            <Button
              text={i18n.t('commons.validate')}
              isSelected={true}
              onPress={handleLogin}
            />
          </ScrollView>
        </View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
  modalContent: {
    width: '90%',
    height: '90%',
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10,
    elevation: 10,
  },
  title: {
    marginBottom: 20,
    fontSize: fonts.title.fontSize,
    fontFamily: fonts.title.fontFamily,
  },
});
