import React, { useCallback } from 'react';
import { View, ScrollView, StyleSheet, KeyboardAvoidingView, Platform, Dimensions } from 'react-native';
import Button from '@/components/Button';
import { useUsers } from '@/contexts/UserContext';
import AppText from '@/components/AppText';
import { router, useLocalSearchParams, useFocusEffect } from 'expo-router';
import { useId4a } from '@/contexts/Id4aContext';
import { useReturnMemory } from '@/contexts/ReturnMemoryContext';
import fichier_4a from '@/assets/json/fichier_4a.json';
import fichier_8a from '@/assets/json/fichier_8a.json';
import { useColor } from '@/contexts/ThemeColorContext';
import { useAppData } from '@/contexts/AppDataContext';


const getDossierSection = (dossier: any, sectionKey: string): any[] => {
  if (!sectionKey || sectionKey === '.') return [];
  if (sectionKey === 'carnetdebord') {
    return dossier?.carnetdebord?.['Carnet de bord'] ?? [];
  }
  return dossier?.[sectionKey] ?? [];
};

const DossierLectureDirect: React.FC = () => {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a } = useAppData();
  const { currentUser } = useUsers();
  const { setBackgroundColor } = useColor();
  const { setId4a } = useId4a();
  const { returnMemory, clearReturnMemory } = useReturnMemory();
  const params = useLocalSearchParams();

  const id_4a_clicked = params.id_4a ? Number(params.id_4a) : undefined;

  useFocusEffect(
    useCallback(() => {
      setBackgroundColor('#FFFFFF');
      // setId4a met à jour le contexte pour que le header se mette à jour
      // mais on n'utilise PAS goBack4a pour la navigation retour
      if (id_4a_clicked) setId4a(id_4a_clicked);
    }, [id_4a_clicked])
  );

  const buildSections = () => {
    if (!id_4a_clicked) return [];
    const node = fichier_4a.find(n => n.id === id_4a_clicked);
    if (!node) return [];

    const childIds: number[] =
      node.id_4a && node.id_4a !== '.'
        ? node.id_4a.toString().split(',').map(Number)
        : [];

    const ids = childIds.length > 0 ? childIds : [id_4a_clicked];

    return ids
      .map(id => {
        const child = fichier_4a.find(n => n.id === id);
        if (!child) return null;
        const entry8 = fichier_8a.find(e => e.id === child.id_8a);
        if (!entry8 || !entry8.sectionkey || entry8.sectionkey === '.') return null;
        const items = getDossierSection(currentUser?.dossier, entry8.sectionkey);
        return { label: child.label, sectionkey: entry8.sectionkey, items };
      })
      .filter(Boolean);
  };

  const sections = buildSections();

  // Fin de lecture → on va où ReturnMemory nous dit d'aller
  const onClose = () => {
    if (returnMemory) {
      const node4a = fichier_4a.find(n => n.id === returnMemory);
      const node8a = fichier_8a.find(n => n.id === node4a?.id_8a);
      clearReturnMemory();
      if (node8a?.href && node8a.href !== '/' && node8a.href !== '/(tabs)') {
        router.replace({ pathname: node8a.href as any, params: { id_4a: returnMemory } });
        return;
      }
    }
    router.back();
  };

  const formatDateOnly = (isoString: string) => {
    const d = new Date(isoString);
    return `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}/${d.getFullYear()}`;
  };

  const renderSection = (section: { label: string; sectionkey: string; items: any[] }) => (
    <View key={section.sectionkey} style={{ marginBottom: 20 }}>
      <AppText
        text={section.label}
        style={{ textAlign: 'center', marginVertical: 10, fontSize: 22, fontWeight: '700' }}
      />
      {section.items.length === 0 ? (
        <AppText text="(Aucun élément)" style={{ textAlign: 'center', fontStyle: 'italic' }} />
      ) : (
        [...section.items].reverse().map((item, index) => (
          <View key={index} style={styles.remarkItem}>
            <View style={{ flexDirection: 'column', flex: 1 }}>
              <AppText style={styles.remarkdate} text={`(${formatDateOnly(item.date)})`} />
              <AppText style={styles.remarkText} text={item.text} />
            </View>
          </View>
        ))
      )}
    </View>
  );

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={[styles.popV2, { width: Dimensions.get('window').width }]}>
        <ScrollView contentContainerStyle={{ padding: 20 }}>
          {sections.length === 0 ? (
            <AppText text="Aucune section à afficher." style={{ textAlign: 'center', fontStyle: 'italic' }} />
          ) : (
            sections.map(renderSection)
          )}
        </ScrollView>
        <View style={styles.centeredContainer}>
          <Button text="Fin de lecture" onPress={onClose} isSelected />
        </View>
      </View>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  popV2: {
    backgroundColor: 'white',
    padding: 20,
    flex: 1,
  },
  centeredContainer: {
    paddingVertical: 20,
    alignItems: 'center',
  },
  remarkItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 5,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  remarkText: {
    fontStyle: 'italic',
  },
  remarkdate: {
    fontStyle: 'italic',
    fontSize: 10,
  },
});

export default DossierLectureDirect;