import React, { useState, useEffect, useContext } from 'react';
import { View, ScrollView, Text, Modal, TouchableOpacity, Pressable, StyleSheet } from 'react-native';
import { Symptome } from '@/constants/type';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { formatDate } from '@/constants/constants';
import RemarquePopup from '@/components/popUp/RemarquePopUp';
import Button from '@/components/Button';
import { InputBox } from '@/components/AssessSymptom';
import { useUsers } from '@/contexts/UserContext';
import Clinimeter from '@/components/Clinimeter';
import i18n from '@/i18n/config';
import EndingBilanPopup from '@/components/popUp/EndingBilanPopUp';
import SymptomInfoPopup from '@/components/popUp/SymptomInfoPopup';
import * as Location from 'expo-location';
import { useReturnMemory } from '@/contexts/ReturnMemoryContext';
import { InformationContext } from '@/contexts/InformationContext';
import { useAppData } from '@/contexts/AppDataContext';
import { useId4r } from "@/contexts/Id4rContext";


// ─────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────

const getSymptomInfo = (symptom: Symptome): string => {
    const info = (symptom as any).Information ?? '';
  if (!info || info === 'X' || info === 'x' || info === '_' || info === '.') return '';
  return info;
};

const createBilan = (
  id3a: number,
  data: Record<number, any>,
  globalData: Map<number, any>,
  filteredSuivi: any[],
  parsedSymptoms: any[]
) => {
  const patho = filteredSuivi.find((p: any) => p.id === id3a);
  if (!patho) return null;
  const symptomIds: number[] = Array.isArray(patho.symptoms)
    ? patho.symptoms.map((s: any) => Number(s.id))
    : (patho.raw?.symptoms ?? '').split(',').map(Number).filter((n: number) => !isNaN(n));
  return {
    id: patho.id,
    name: patho.name,
    date: new Date().toISOString(),
    symptoms: symptomIds.map((id: number) => {
      const s = parsedSymptoms.find((sym: any) => sym.id === id);
      const lastValue = globalData?.get(id)?.values?.at(-1)?.valeur ?? null;
      return { id, name: s?.name || 'Unknown symptom', value: data[id] ?? lastValue };
    }),
  };
};

// ─────────────────────────────────────────────
// SymptomRow — ligne titre cliquable
// ─────────────────────────────────────────────

type SymptomRowProps = {
  symptom: Symptome;
  leftButton: React.ReactNode;
  centerValue: React.ReactNode;
  rightButton: React.ReactNode;
  onInfoPress: (symptom: Symptome) => void;
};

const SymptomRow: React.FC<SymptomRowProps> = ({
  symptom, leftButton, centerValue, rightButton, onInfoPress,
}) => {
  const info = getSymptomInfo(symptom);
  const hasInfo = !!info;
  const isOuiNonEval = leftButton || rightButton;

  return (
    <View style={{ width: '100%' }}>
      {isOuiNonEval ? (
        <>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
            <TouchableOpacity onPress={() => hasInfo && onInfoPress(symptom)} activeOpacity={hasInfo ? 0.6 : 1}>
              <Text style={rowStyles.title}>
                {symptom.surname}{hasInfo ? <Text style={rowStyles.infoIcon}> ⓘ</Text> : ''}
              </Text>
            </TouchableOpacity>
            <View style={{ width: '40%', alignItems: 'center' }}>{centerValue}</View>
          </View>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
            <View />
            <View style={{ width: '40%', flexDirection: 'row', justifyContent: 'space-between' }}>
              <View>{leftButton}</View>
              <View>{rightButton}</View>
            </View>
          </View>
        </>
      ) : (
        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
          <TouchableOpacity
            onPress={() => hasInfo && onInfoPress(symptom)}
            activeOpacity={hasInfo ? 0.6 : 1}
            style={{ flex: 0.6 }}
          >
            <Text style={[rowStyles.title, hasInfo && rowStyles.titleClickable]}>
              {symptom.surname}{hasInfo ? ' ⓘ' : ''}
            </Text>
          </TouchableOpacity>
          <View style={{ flex: 0.4, alignItems: 'flex-end' }}>{centerValue}</View>
        </View>
      )}
    </View>
  );
};

const rowStyles = StyleSheet.create({
  title: { fontSize: 18, fontWeight: 'bold' },              // noir, pas souligné
  titleClickable: { color: '#E8437B', textDecorationLine: 'underline' },  // plus utilisé, tu peux le supprimer
  infoIcon: { color: '#E8437B', textDecorationLine: 'none' }, // ⓘ rouge uniquement
});

// ─────────────────────────────────────────────
// Page principale
// ─────────────────────────────────────────────

const SymptomsAssociatedWithSuivi: React.FC = () => {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a, filteredSuivi, parsedSymptoms } = useAppData();

  const { evaluateur, id_suivi } = useLocalSearchParams<{ evaluateur?: string; id_suivi?: any }>();
  const router = useRouter();
  const { returnMemory, clearReturnMemory } = useReturnMemory();
  const { currentUser, addDataToGlobal, volatileData, clearVolatile, saveBilan, getLastValueForUser, persistNow } = useUsers();
  const { setinfoText } = useContext(InformationContext);
  const { setId4r, home4r } = useId4r(); // home4r → retour vers 4r si session active

  const pathId = Number(id_suivi);
  const pathologieEntry = filteredSuivi.find(p => p.id === pathId) ?? null;
  const symptoms = pathologieEntry ? (pathologieEntry.symptoms as Symptome[]) : [];

  // ── information / score
  const rawInformation: string = (pathologieEntry as any)?.raw?.information ?? '';
  const infoParts = rawInformation.trim().split(/\s+/);
  const showScore = infoParts[0] === 'Score';
  const infoImageForToolbar = showScore ? infoParts.slice(1).join(' ') : rawInformation;

  // ── override de valMax via le champ "couleur" du bilan (ex: "base 7" → 7)
  const valMaxOverride: number | undefined = (pathologieEntry as any)?.valMaxOverride;

  // ── state
  const [commitRequested, setCommitRequested] = useState(false);
  const CLINIMETER_IDS = [12, 13, 14, 15, 19, 35];
  const [clinimeterPathId, setClinimeterPathId] = useState<number | null>(null);
  const [askRemarqueVisible, setAskRemarqueVisible] = useState(false);
  const [remarquePopupVisible, setRemarquePopupVisible] = useState(false);
  const [graphiquePopupVisible, setGraphiquePopupVisible] = useState(false);
  const [freshBilan, setFreshBilan] = useState<any>(null);
  const [infoPopupSymptom, setInfoPopupSymptom] = useState<Symptome | null>(null);

  useEffect(() => { if (infoImageForToolbar) setinfoText(infoImageForToolbar); }, [infoImageForToolbar]);
  useEffect(() => { setClinimeterPathId(null); }, [id_suivi]);
  // Nettoie id4r quand on quitte le bilan (retour vers navigation normale)
  useEffect(() => { return () => setId4r(null); }, []);

  // ── score
  const qualifyingSymptoms = symptoms.filter(s => s.type === 'Oui/non éval');
  const computeScore = () => {
    let total = 0, maxTotal = 0;
    qualifyingSymptoms.forEach(s => {
      const val = (volatileData[s.id] != null) ? volatileData[s.id] : getLastValueForUser(s.id, currentUser?.username ?? '');
      if (val != null && val !== '') {
        const sMax = typeof s.valMax === 'string' ? parseFloat(s.valMax) : (typeof s.valMax === 'number' ? s.valMax : 10);
        total += Number(val);
        maxTotal += sMax;
      }
    });
    return { total, maxTotal };
  };
  const { total: valeurTotale, maxTotal: valeurMaxTotale } = computeScore();

  // ── navigation
  const navigateAway = () => {
    if (returnMemory) {
      const n4 = fichier_4a.find(n => n.id === returnMemory);
      if (n4?.id_8a) {
        const n8 = fichier_8a.find(n => n.id === n4.id_8a);
        if (n8?.href) { clearReturnMemory(); router.push({ pathname: n8.href, params: { id_4a: returnMemory } }); return; }
      }
    }
    clearReturnMemory();
    // ── Si session 4r active → retour sur l'écran d'accueil 4r (pas /(tabs)) ──
    if (home4r !== null) {
      router.push({
        pathname: '/(tabs)/post_carrefour/bilanlike',
        params: { id_4r: String(home4r.id4r), id_4a: String(home4r.id4a) },
      });
      return;
    }
    router.push('/(tabs)');
  };

  // ── sauvegarde
  const handleFinalSave = async (remarque: string | null) => {
    setAskRemarqueVisible(false);
    setRemarquePopupVisible(false);
    setCommitRequested(true);

    let latitude = null, longitude = null;
    try {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status === 'granted') {
        const loc = await Promise.race([
          Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Low }),
          new Promise<null>(resolve => setTimeout(() => resolve(null), 3000)),
        ]);
        if (loc && 'coords' in loc) { latitude = loc.coords.latitude; longitude = loc.coords.longitude; }
      }
    } catch {}

    const { total: ft, maxTotal: fmt } = computeScore();
    const allData: Record<number, any> = {};
    symptoms.forEach(s => {
      const val = (volatileData[s.id] != null) ? volatileData[s.id] : getLastValueForUser(s.id, currentUser?.username ?? '');
      if (val != null) allData[s.id] = val;
    });

    const bilanBase = createBilan(pathId, allData, currentUser.globalData, filteredSuivi, parsedSymptoms);
    if (bilanBase) {
      const bilan = {
        ...bilanBase, latitude, longitude,
        evaluateur: currentUser?.evaluateur ?? null,
        patient: currentUser?.username ?? null,
        remarque: remarque ?? null,
        valeurTotale: showScore ? ft : undefined,
        valeurMaxTotale: showScore ? fmt : undefined,
      };
      await saveBilan(bilan);
      setFreshBilan(bilan);
    }

    clearVolatile();
    await persistNow();
    if (CLINIMETER_IDS.includes(pathId)) setGraphiquePopupVisible(true);
    else navigateAway();
  };

  const showingClinimeter = clinimeterPathId !== null;

  return (
    <ScrollView contentContainerStyle={{ paddingBottom: 70 }}>
      {clinimeterPathId !== null ? (
        <Clinimeter
          pathos={filteredSuivi.find((p: any) => p.id === clinimeterPathId)}
          freshBilan={freshBilan}
        />
      ) : (
        <>
          {symptoms.map(symptom => {
            const initialSliderValue = getLastValueForUser(symptom.id, currentUser?.username ?? '');
            const formattedDate = symptom.data?.at(-1)?.date ? formatDate(new Date(symptom.data.at(-1).date)) : null;

            // Si le bilan a un valMaxOverride (ex: MIF → 7), on scale la valeur init sauvegardée :
            // ancienneValeur / valMaxOriginal * valMaxOverride, arrondi au plus proche.
            let scaledInitValue: number | null = typeof initialSliderValue === 'number' ? initialSliderValue : null;
            if (scaledInitValue !== null && valMaxOverride !== undefined) {
              const origMax =
                typeof symptom.valMax === 'number' ? symptom.valMax :
                typeof symptom.valMax === 'string' ? parseFloat(symptom.valMax) :
                10;
              if (!isNaN(origMax) && origMax > 0) {
                scaledInitValue = Math.round(scaledInitValue / origMax * valMaxOverride);
              }
            }

            return (
              <View key={symptom.id} style={{ padding: 5 }}>
                <InputBox
                  s={symptom}
                  evaluateur={evaluateur?.toString()}
                  onClose={() => {}}
                  noText donotdispVButtons ouinonSameLine
                  valMaxOverride={valMaxOverride}
                  initsetSliderValue={scaledInitValue !== null ? scaledInitValue : undefined}
                  lastValueDate={formattedDate}
                  recupSliderValue={v => addDataToGlobal(symptom.id, { date: new Date(), valeur: v, evaluateur: currentUser?.evaluateur ?? null, patient: currentUser?.username ?? null })}
                  recupYesNo={v => addDataToGlobal(symptom.id, { date: new Date(), valeur: v ? 1 : 0, evaluateur: currentUser?.evaluateur ?? null, patient: currentUser?.username ?? null })}
                  initsetTexteValue={scaledInitValue !== null ? String(scaledInitValue) : undefined}
                  commitRequested={commitRequested}
                >
                  {({ leftButton, centerValue, rightButton }) => (
                    <SymptomRow
                      symptom={symptom}
                      leftButton={leftButton}
                      centerValue={centerValue}
                      rightButton={rightButton}
                      onInfoPress={s => setInfoPopupSymptom(s)}
                    />
                  )}
                </InputBox>
              </View>
            );
          })}
        </>
      )}

      {showScore && valeurMaxTotale > 0 && !showingClinimeter && (
        <View style={{ alignItems: 'center', paddingVertical: 16 }}>
          <Text style={{ fontSize: 28, fontWeight: 'bold', color: '#333' }}>{valeurTotale} / {valeurMaxTotale}</Text>
          <Text style={{ fontSize: 12, color: '#888', marginTop: 4 }}>Score total</Text>
        </View>
      )}

      {showingClinimeter ? (
        <Button isSelected onPress={navigateAway} text="Retour à l'accueil" />
      ) : (
        <Button isSelected onPress={() => setAskRemarqueVisible(true)} text={i18n.t('commons.validate')} />
      )}

      {!showingClinimeter && (
        <>
          <EndingBilanPopup
            visible={askRemarqueVisible}
            onClose={text => handleFinalSave(text ?? null)}
            onCloseGoBack={() => { setAskRemarqueVisible(false); setRemarquePopupVisible(true); }}
          />
          <RemarquePopup
            visible={remarquePopupVisible}
            onClose={() => handleFinalSave(null)}
            sectionKey="remarques" sectionLabel="remarque"
            onSubmit={text => handleFinalSave(text)}
          />
        </>
      )}

      {/* Modal graphique */}
      <Modal transparent visible={graphiquePopupVisible} animationType="fade">
        <View style={styles.backdrop}>
          <View style={styles.card}>
            <Text style={{ fontSize: 16, fontWeight: 'bold', textAlign: 'center', marginBottom: 20 }}>
              Voulez-vous générer un graphique ?
            </Text>
            <View style={{ flexDirection: 'row', gap: 12 }}>
              <Button isSelected text={i18n.t('commons.yes')} onPress={() => { setGraphiquePopupVisible(false); setClinimeterPathId(pathId); }} />
              <Button isSelected text={i18n.t('commons.no')} onPress={() => { setGraphiquePopupVisible(false); navigateAway(); }} />
            </View>
          </View>
        </View>
      </Modal>

      {/* Popup info symptôme */}
      <SymptomInfoPopup
        visible={!!infoPopupSymptom}
        title={infoPopupSymptom?.name ?? ''}
        text={infoPopupSymptom ? getSymptomInfo(infoPopupSymptom) : ''}
        onClose={() => setInfoPopupSymptom(null)}
      />
    </ScrollView>
  );
};

export default SymptomsAssociatedWithSuivi;

const styles = StyleSheet.create({
  backdrop: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.5)' },
  card: { backgroundColor: 'white', borderRadius: 12, padding: 24, width: '80%', alignItems: 'center' },
});