import React, { useEffect, useState } from 'react';
import { View, StyleSheet, Modal } from 'react-native';
import { useAuth } from '@/contexts/AuthContext';
import Button from '@/components/Button';
import AppText from '@/components/AppText';
import i18n from '@/i18n/config';
import { basic_data_result, calculateBMI, formatDate } 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 ModifyBasicDataPopUp({ visible, onClose }: ModalProps) {
  const { currentUser, updateCurrentUserAsync } = useUsers();

  // 🔥 Toujours un tableau, jamais undefined
  const [textInputValues, setTextInputValues] = useState<Symptome[]>(
    Array.isArray(currentUser?.basic_data) ? currentUser.basic_data : []
  );

  const [allSymptoms, setAllSymptoms] = useState<Symptome[]>([]);

  // 🔥 Recharge proprement quand currentUser change
  useEffect(() => {
    if (Array.isArray(currentUser?.basic_data)) {
      setTextInputValues(currentUser.basic_data);
    } else {
      setTextInputValues([]);
    }
  }, [currentUser]);

  // 🔥 Validation
  const handleLogin = async () => {
    await updateCurrentUserAsync({ basic_data: textInputValues });
    onClose();
  };

  // 🔥 Construction de allSymptoms (sécurisé)
  useEffect(() => {
    const activePathologies =
      Array.isArray(currentUser?.bilan)
        ? currentUser.bilan.filter(p => !p.ended)
        : [];

    if (currentUser?.custom_suivi && !currentUser.custom_suivi.ended) {
      activePathologies.push(currentUser.custom_suivi);
    }

    if (Array.isArray(currentUser?.suivi)) {
      activePathologies.push(
        ...currentUser.suivi.filter(p => !p.ended)
      );
    }

    let allSymptomsArray: Symptome[] =
      Array.isArray(currentUser?.basic_data) ? currentUser.basic_data : [];

    activePathologies.forEach(pathology => {
      if (Array.isArray(pathology?.symptoms)) {
        const symptomsWithPathology = pathology.symptoms.map(symptom => ({
          ...symptom,
          pathologyName: pathology.name,
        }));
        allSymptomsArray = allSymptomsArray.concat(symptomsWithPathology);
      }
    });

    // 🔥 Sécurisation : Set ne marche pas sur objets → on déduplique par ID
    const unique = new Map<number, Symptome>();
    allSymptomsArray.forEach(s => unique.set(s.id, s));

    setAllSymptoms(Array.from(unique.values()));
  }, [currentUser]);

  // 🔥 Mise à jour d’un champ
  const handleTextInputChange = (id: number, value: string | number) => {
    setTextInputValues(prev => {
      const safePrev = Array.isArray(prev) ? prev : [];
      const existing = safePrev.find(s => s.id === id);

      if (existing) {
        return safePrev.map(s =>
          s.id === id
            ? {
                ...s,
                data: [
                  ...s.data,
                  { date: new Date(), valeur: value }
                ],
              }
            : s
        );
      }

      const newSymptom = basic_data_result.find(s => s.id === id);
      if (newSymptom) {
        return [
          ...safePrev,
          {
            ...newSymptom,
            data: [{ date: new Date(), valeur: value }],
          },
        ];
      }

      return safePrev;
    });
  };

  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);

  // 🔥 Calcul IMC automatique
  useEffect(() => {
    if (!Array.isArray(textInputValues)) return;

    const tailleEntry = textInputValues.find(s => s.id === 41);
    const poidsEntry = textInputValues.find(s => s.id === 42);

    if (!tailleEntry || !poidsEntry) return;

    const taille = Number(tailleEntry.data.at(-1)?.valeur);
    const poids = Number(poidsEntry.data.at(-1)?.valeur);

    if (!taille || !poids || taille <= 0 || poids <= 0) return;

    const bmi = calculateBMI(String(poids), String(taille));
    const currentBMI = textInputValues.find(s => s.id === 43)?.data?.at(-1)?.valeur;

    if (bmi && bmi !== currentBMI) {
      handleTextInputChange(43, bmi);
    }
  }, [textInputValues]);

  // 🔥 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.basic_data.title')}
            style={styles.title}
          />

          <ScrollView>
            {basic_data_result.map(symptom => {
              const found = safeFind(symptom.id);
              const lastValue = found?.data?.at(-1)?.valeur;
              const lastDate = found?.data?.at(-1)?.date;
              const formattedDate = lastDate ? formatDate(new Date(lastDate)) : null;

              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={
                      typeof lastValue === 'number' ? lastValue : undefined
                    }
                    initsetTexteValue={
                      symptom.type === 'Texte' || symptom.type === 'rangeRegex'
                        ? String(lastValue ?? '')
                        : undefined
                    }
                    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
                    lastValueDate={formattedDate}
                  />
                </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,
  },
});
