import React, { useEffect, useState, useContext, useRef, useCallback } from 'react';
import { FlatList, Text, StyleSheet, Pressable, Image, View } from 'react-native';
import fichier_4a from '@/assets/json/fichier_4a.json';
import fichier_8a from '@/assets/json/fichier_8a.json';
import { getIconPath } from '@/constants/constants';
import { Pathologie } from '@/constants/type';
import AppText from '@/components/AppText';
import { useLocalSearchParams, useRouter, useFocusEffect } from 'expo-router';
import pathologiesJSON from '@/assets/json/pathologie_parsed.json';
import { TitleContext } from '@/contexts/TitleContext';
import { ImageContext } from '@/contexts/ImageContext';
import Button from '@/components/Button';
import { useId4a } from "@/contexts/Id4aContext";
import { useId4r } from "@/contexts/Id4rContext";
import { useId3a } from "@/contexts/Id3aContext";
import AntDesign from "@expo/vector-icons/AntDesign";
import { useReturnMemory } from "@/contexts/ReturnMemoryContext";
import UsernamePopUp from '@/components/popUp/UsernamePopUp';
import DeleteProfilePopUp from '@/components/popUp/DeleteProfilePopUp';
import { DataTransferPopup } from '@/components/popUp/Datatransferpopup';
import { useAdmin } from '@/contexts/AdminContext';
import { useColor } from '@/contexts/ThemeColorContext';
import { useAppData } from '@/contexts/AppDataContext';


const SAFE_FALLBACK = '/(tabs)/index2';

const isValidHref = (href: string | undefined): boolean => {
  if (!href) return false;
  if (href === '/' || href === '/(tabs)') return false;
  return true;
};

const Listnaturo: React.FC = () => {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a, fichier4r } = useAppData();
  const [activePopup, setActivePopup] = useState<string | null>(null);
  const [PopupComponent, setPopupComponent] = useState<React.FC | null>(null);
  // parse4rChildren : fonction pure, peut rester ici
  const parse4rChildren = (id4r: any): number[] => {
    if (!id4r || String(id4r) === '.') return [];
    const str = String(id4r);
    if (str.includes(',')) return str.split(',').map(Number).filter(n => !isNaN(n) && n > 0);
    if (str.includes('.')) return str.split('.').map(Number).filter(n => !isNaN(n) && n > 0);
    const n = Number(str);
    return (!isNaN(n) && n > 0) ? [n] : [];
  };

  const POPUP_COMPONENTS: Record<string, React.FC<any>> = {
    UsernamePopUp: UsernamePopUp,
    DeleteProfilePopUp: DeleteProfilePopUp,
    Datatransferpopup: DataTransferPopup,
  };

  const { isAdmin } = useAdmin();
  const { backgroundColor, setBackgroundColor, getContrastColor } = useColor();

  const openPopup = (popupName: string) => {
    const Component = POPUP_COMPONENTS[popupName];
    if (!Component) { console.error("❌ Popup introuvable :", popupName); return; }
    setPopupComponent(() => Component);
    setActivePopup(popupName);
  };

  const closePopup = () => { setActivePopup(null); setPopupComponent(null); };

  const { id4a, history, setId4a, goBack4a } = useId4a();
  const { setId4r, setHome4r } = useId4r();
  const { setId3a } = useId3a();
  const { setReturnMemory } = useReturnMemory();

  const params = useLocalSearchParams();
  const id_4a_clicked = params.id_4a ? Number(params.id_4a) : undefined;
  const id4rParam = params.id_4r ? String(params.id_4r) : null;
  const id4aParam = params.id_4a ? String(params.id_4a) : null;

  // ── Valeurs dérivées du mode 4r (déclarées ici, après tous les hooks) ────
  const is4rMode      = !!id4rParam;
  const current4rId   = is4rMode ? Number(id4rParam) : null;
  const current4rNode = current4rId ? (fichier4r as any[]).find(n => n.id === current4rId) ?? null : null;
  const child4rNodes  = current4rNode
    ? parse4rChildren(current4rNode.id_4r)
        .map((id: number) => (fichier4r as any[]).find(n => n.id === id))
        .filter(Boolean)
    : [];
  // ─────────────────────────────────────────────────────────────────────────

  const { setImageProp } = useContext(ImageContext);
  const { setTitle } = useContext(TitleContext);
  const router = useRouter();

  // ── handleItem4rPress : clone complet de handleItemPress4a mais pour fichier_4r ──
  const handleItem4rPress = useCallback((node: any) => {
    setId4r(node.id);

    // returnmemory
    if (node.returnmemory && node.returnmemory !== '.') setReturnMemory(Number(node.returnmemory));

    // titre + couleur
    setTitle(node.label ?? '');
    if (node.couleur && node.couleur !== '.') {
      lastValidColor.current = node.couleur;
      setBackgroundColor(node.couleur);
    } else if (node.information && typeof node.information === 'string' && node.information.startsWith('#')) {
      lastValidColor.current = node.information;
      setBackgroundColor(node.information);
    }

    // id_3a → bilan direct
    if (node.id_3a && String(node.id_3a) !== '.') {
      router.push({
        pathname: '/(tabs)/bilan/symptoms_associated_with_bilan',
        params: { id_suivi: String(node.id_3a) },
      });
      return;
    }

    // id_4r → enfants dans fichier_4r
    const children4r = parse4rChildren(node.id_4r);
    if (children4r.length > 0) {
      if (children4r.length === 1) {
        // raccourci : un seul enfant → navigation directe
        const solo = (fichier4r as any[]).find(n => n.id === children4r[0]);
        if (solo) { handleItem4rPress(solo); return; }
      }
      router.push({
        pathname: '/(tabs)/post_carrefour/bilanlike',
        params: { id_4r: String(node.id), id_4a: id4aParam ?? '' },
      });
      return;
    }

    // id_8a → href (popup, écran valide, dossier_lecture fallback)
    let href: string | undefined = undefined;
    if (node.id_8a) href = fichier_8a.find((e: any) => e.id === node.id_8a)?.href;
    if (href?.startsWith('popup:')) { openPopup(href.replace('popup:', '')); return; }
    if (href && isValidHref(href)) {
      router.push({ pathname: href as string, params: { id_4r: String(node.id) } });
      return;
    }

    // fallback
    router.push({
      pathname: '/(tabs)/bilan/dossier_lecture',
      params: { label: node.label, id_4r: String(node.id) },
    });
  }, [router, setId4r, setReturnMemory, setTitle, id4aParam, openPopup]);
  // ──────────────────────────────────────────────────────────────────

  const [isSpecialCase, setIsSpecialCase] = useState(false);
  const [specialCaseData, setSpecialCaseData] = useState<any[]>([]);
  const [filteredSuiviData, setFilteredSuiviData] = useState<any[]>([]);

  const lastValidColor = useRef("#FFFFFF");

  const getFilteredData = (id_4a: string | null) => {
    if (!id_4a || id_4a === ".") return [];
    const ids = id_4a.toString().split(',').map(Number);
    return ids.map(id => fichier_4a.find(item => item.id === id)).filter(Boolean);
  };

  const handleItemPress = useCallback((id: number) => {
    setId3a(id);
    const pathology = pathologiesJSON.find(it => it.id === id);
    if (pathology?.logo) setImageProp(pathology.logo);
    setTitle(pathology?.name || '');
    router.push({ pathname: '/(tabs)/bilan/symptoms_associated_with_bilan', params: { id_suivi: id } });
  }, [router, setId3a, setImageProp, setTitle]);

  const handleItemPress4a = useCallback((item: any) => {
    if (item.returnmemory && item.returnmemory !== ".") setReturnMemory(Number(item.returnmemory));

    setId4a(item.id);

    const node = fichier_4a.find(el => el.id === item.id);
    if (node) {
      setTitle(node.label);
      if (node.couleur && node.couleur !== ".") {
        lastValidColor.current = node.couleur;
        setBackgroundColor(node.couleur);
      } else if (node.information && typeof node.information === 'string' && node.information.startsWith("#")) {
        lastValidColor.current = node.information;
        setBackgroundColor(node.information);
      }
    }

    // ── Détection id_4r (même logique que loginrose) ────────────────
    const raw4r = (item as any).id_4r;
    if (raw4r !== undefined && raw4r !== null && String(raw4r) !== '.' && Number(raw4r) !== 0) {
      setId4r(Number(raw4r));
      setHome4r({ id4r: Number(raw4r), id4a: item.id });
      router.push({
        pathname: '/(tabs)/post_carrefour/bilanlike',
        params: { id_4r: String(raw4r), id_4a: String(item.id) },
      });
      return;
    }
    // ─────────────────────────────────────────────────────────────────

    let href: string | undefined = undefined;
    if (item.id_8a) href = fichier_8a.find(e => e.id === item.id_8a)?.href;

    if (href?.startsWith("popup:")) { openPopup(href.replace("popup:", "")); return; }

    if (!isValidHref(href)) {
      router.push({ pathname: '/(tabs)/bilan/dossier_lecture', params: { label: item.label, id_4a: item.id } });
      return;
    }

    router.push({ pathname: href as string, params: { id_4a: item.id } });
  }, [router, setId4a, setId4r, setHome4r, setReturnMemory, setTitle]);

  useFocusEffect(
    useCallback(() => {
      if (!id_4a_clicked) {
        setBackgroundColor("#FFFFFF");
        return;
      }

      // ── Mode 4r : traitement complet (clone du traitement 4a) ────────
      if (is4rMode) {
        if (!current4rNode) return;
        setId4r(current4rId);
        setTitle(current4rNode.label ?? '');
        const col = current4rNode.couleur;
        if (col && col !== '.') { lastValidColor.current = col; setBackgroundColor(col); }

        // id_3a direct sur le nœud courant
        if (current4rNode.id_3a && String(current4rNode.id_3a) !== '.') {
          router.push({
            pathname: '/(tabs)/bilan/symptoms_associated_with_bilan',
            params: { id_suivi: String(current4rNode.id_3a) },
          });
          return;
        }

        // raccourci un seul enfant
        if (child4rNodes.length === 1) {
          handleItem4rPress(child4rNodes[0]);
          return;
        }
        return;
      }
      // ─────────────────────────────────────────────────────────────────
      setId4r(null); // mode normal → désactiver le contexte 4r
      setIsSpecialCase(false);
      setSpecialCaseData([]);
      setFilteredSuiviData([]);
      setId3a(undefined);

      const node = fichier_4a.find(el => el.id === id_4a_clicked);
      if (!node) return;

      setId4a(id_4a_clicked);
      setTitle(node.label);

      // Couleur : utilise couleur, sinon information si c'est un hex, sinon lastValidColor
      let couleur: string;
      if (node.couleur && node.couleur !== ".") {
        couleur = node.couleur;
      } else if (node.information && typeof node.information === 'string' && node.information.startsWith("#")) {
        couleur = node.information;
      } else {
        couleur = lastValidColor.current;
      }
      lastValidColor.current = couleur;
      setBackgroundColor(couleur);

      if (node.id_3a && node.id_3a !== "." && node.id_3a !== "") {
        handleItemPress(Number(node.id_3a));
        return;
      }

      if (node.id_4a && node.id_4a !== ".") {
        const data = getFilteredData(node.id_4a);

        // ── Si une seule destination : navigation directe, pas de liste ──
        if (data.length === 1) {
          handleItemPress4a(data[0]);
          return;
        }

        setIsSpecialCase(true);
        setSpecialCaseData(data);
        return;
      }

    }, [id_4a_clicked, is4rMode, current4rNode, child4rNodes, handleItemPress, handleItemPress4a, handleItem4rPress])
  );

  const handleBack = useCallback(() => {
    if (router.canGoBack()) {
      router.back();
      return;
    }
    const backId = goBack4a();
    if (!backId) { router.replace('/(tabs)'); return; }
    const node4a = fichier_4a.find(n => n.id === backId);
    if (!node4a) { router.replace('/(tabs)'); return; }
    const node8a = fichier_8a.find(n => n.id === node4a.id_8a);
    const href = node8a?.href;
    if (!isValidHref(href)) { router.replace('/(tabs)'); return; }
    router.push({ pathname: href as string, params: { id_4a: backId } });
  }, [goBack4a, router]);

  const currentNode = is4rMode
    ? (fichier4r as any[]).find(el => el.id === current4rId)
    : fichier_4a.find(el => el.id === id_4a_clicked);
  const isAdminPage = currentNode?.information === "Page réservée aux administrateurs";

  // Masquer la flèche retour si information contient "noback"
  const hideBack = typeof currentNode?.information === 'string' && currentNode.information.includes("noback");

  if (isAdminPage && !isAdmin) {
    return (
      <View style={[styles.listContainer, { backgroundColor, flex: 1, justifyContent: 'center', alignItems: 'center' }]}>
        <View style={{ position: "absolute", top: 40, left: 20, zIndex: 50 }}>
          <Pressable onPress={handleBack}>
            <AntDesign name="arrowleft" size={32} color={getContrastColor(backgroundColor)} />
          </Pressable>
        </View>
        <Text style={{ textAlign: 'center', padding: 30, fontSize: 16, color: getContrastColor(backgroundColor) }}>
          Cette page est réservée aux administrateurs. Veuillez renseigner votre code si vous en êtes un en retournant dans les premières pages depuis profil.
        </Text>
      </View>
    );
  }

  return (
    <View style={[styles.listContainer, { backgroundColor }]}>
      {is4rMode ? (
        /* ── Mode navigation 4r ── */
        <FlatList
          data={child4rNodes}
          keyExtractor={item => String(item.id)}
          contentContainerStyle={{ flexGrow: 1, justifyContent: 'flex-start', paddingTop: 100, alignItems: 'flex-start' }}
          renderItem={({ item }) => (
            <Button
              text={item.label ?? ''}
              onPress={() => handleItem4rPress(item)}
              style={[styles.itemContainer, { backgroundColor }]}
              textStyle={{ color: getContrastColor(backgroundColor) }}
            />
          )}
        />
      ) : (
        /* ── Mode normal 4a ── */
        <FlatList
          data={isSpecialCase ? specialCaseData : filteredSuiviData}
          renderItem={isSpecialCase ? renderItem4a : renderItem}
          keyExtractor={item => item.id.toString()}
          contentContainerStyle={{ flexGrow: 1, justifyContent: 'flex-start', paddingTop: 100, alignItems: 'flex-start' }}
        />
      )}
      {activePopup && PopupComponent && (
        <View style={styles.popupOverlay}>
          <View style={styles.popupContainer}>
            <PopupComponent onClose={closePopup} visible={true} />
          </View>
        </View>
      )}

      {/* Flèche retour masquée si information contient "noback" */}
      {!hideBack && (
        <View style={{ position: "absolute", top: 621, left: 20, zIndex: 50 }}>
          <Pressable onPress={handleBack}>
            <AntDesign name="arrowleft" size={32} color={getContrastColor(backgroundColor)} />
          </Pressable>
        </View>
      )}
    </View>
  );

  function renderItem({ item }: { item: Pathologie }) {
    return (
      <Pressable
        style={({ pressed }) => [styles.itemContainer, { backgroundColor }, pressed && styles.pressedItem]}
        onPress={() => handleItemPress(item.id)}
      >
        <View style={styles.itemIconContainer}>
          <Image style={styles.itemIcon} source={getIconPath(pathologiesJSON.find(it => it.id === item.id)?.logo)} />
        </View>
        <View style={styles.itemTitleContainer}>
          <AppText style={[styles.itemTitle, { color: getContrastColor(backgroundColor) }]} text={item.name || ''} />
        </View>
      </Pressable>
    );
  }

  function renderItem4a({ item }: { item: any }) {
    return (
      <Button
        text={item.label || ''}
        onPress={() => handleItemPress4a(item)}
        style={[styles.itemContainer, { backgroundColor }]}
        textStyle={{ color: getContrastColor(backgroundColor) }}
      />
    );
  }
};

const styles = StyleSheet.create({
  listContainer: { flex: 1, justifyContent: 'center', alignItems: 'flex-start' },
  itemContainer: { flexDirection: 'row', alignItems: 'center', paddingVertical: 16, paddingHorizontal: 24, backgroundColor: '#ffffff', marginTop: 10, marginHorizontal: 5, borderRadius: 5 },
  pressedItem: { backgroundColor: '#e0e0e0' },
  itemIconContainer: { marginRight: 16 },
  itemIcon: { width: 40, height: 40 },
  itemTitleContainer: { flex: 1 },
  itemTitle: { fontSize: 16, color: '#000000' },
  popupOverlay: { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, backgroundColor: "rgba(0,0,0,0.5)", justifyContent: "center", alignItems: "center", zIndex: 999 },
  popupContainer: { width: "90%", backgroundColor: "white", padding: 20, borderRadius: 12 },
});

export default Listnaturo;