import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  ScrollView,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  Dimensions,
  TouchableOpacity,
  Modal,
  TextInput,
} from 'react-native';
import { AntDesign } from '@expo/vector-icons';
import Button from '@/components/Button';
import { useUsers } from '@/contexts/UserContext';
import AppText from '@/components/AppText';
import { router, useLocalSearchParams } from 'expo-router';
import YesNoDossierPopUp from '@/components/popUp/YesNoDossierPopUp';
import { useId4a } from "@/contexts/Id4aContext";
import { useId3a } from "@/contexts/Id3aContext";
import { useFocusEffect } from "@react-navigation/native";
import RemarquePopup from "@/components/popUp/RemarquePopUp";
import { useColor } from '@/contexts/ThemeColorContext';
import colors from '@/styles/colors';
import layout from '@/styles/layout';
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] ?? [];
};

type Props = {
  isVisible?: boolean;
  onClose?: () => void;
  skipToRemarkSection?: boolean;
};

const DossierPage: React.FC<Props> = ({ isVisible, onClose, skipToRemarkSection }) => {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a } = useAppData();
  const { id4a, setId4a } = useId4a();
  const { setId3a } = useId3a();
  const { currentUser, updateCurrentUser } = useUsers();
  const { id_4a: id4aParam } = useLocalSearchParams<{ id_4a?: string }>();
  const resolvedId4a = id4aParam ? Number(id4aParam) : 90;
  const currentNode = fichier_4a.find(n => n.id === resolvedId4a);
  const { setBackgroundColor } = useColor();

  useFocusEffect(
    useCallback(() => {
      setId4a(resolvedId4a);
      setId3a(undefined);
      setBackgroundColor('#FFFFFF');
    }, [resolvedId4a])
  );

  const children4a = currentNode?.id_4a && currentNode.id_4a !== '.'
    ? currentNode.id_4a.split(',').map(Number)
    : [];

  const buttons = children4a
    .map(id => fichier_4a.find(n => n.id === id))
    .filter(Boolean);

  const dossier = currentUser?.dossier ?? {};

  const [showSection, setShowSection] = useState<string | null>(null);
  const [showSectionLabel, setShowSectionLabel] = useState<string | null>(null);
  const [currentSectionKey, setCurrentSectionKey] = useState<string | null>(null);
  const [hideDateInSection, setHideDateInSection] = useState<boolean>(false);
  const [isPopupVisible, setIsPopupVisible] = useState(false);
  const [isV, setIsV] = useState<boolean>(false);

  // ── état édition ──────────────────────────────────────────────
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [editingText, setEditingText] = useState('');
  // ─────────────────────────────────────────────────────────────

  useEffect(() => {
    if (skipToRemarkSection) {
      const remarquesNode = buttons.find(btn => {
        const e8 = fichier_8a.find(e => e.id === btn?.id_8a);
        return e8?.sectionkey === 'remarks';
      });
      if (remarquesNode) {
        const e8 = fichier_8a.find(e => e.id === remarquesNode.id_8a);
        setShowSection(e8?.href?.replace('popup:', '') ?? 'remarques');
        setShowSectionLabel(remarquesNode.label);
        setCurrentSectionKey(e8?.sectionkey ?? 'remarks');
        setHideDateInSection(remarquesNode.information === 'nodate');
      }
    }
  }, [skipToRemarkSection]);

  const currentSectionItems = currentSectionKey
    ? getDossierSection(dossier, currentSectionKey)
    : [];

  // ── sauvegarde de la modification ────────────────────────────
  const handleSaveEdit = () => {
    if (editingIndex === null || !currentSectionKey) return;

    const section = getDossierSection(dossier, currentSectionKey);
    const updatedSection = section.map((item: any, i: number) =>
      i === editingIndex ? { ...item, text: editingText } : item
    );

    let updatedDossier: any = { ...dossier };
    if (currentSectionKey === 'carnetdebord') {
      updatedDossier = {
        ...updatedDossier,
        carnetdebord: {
          ...updatedDossier.carnetdebord,
          'Carnet de bord': updatedSection,
        },
      };
    } else {
      updatedDossier = { ...updatedDossier, [currentSectionKey]: updatedSection };
    }

    updateCurrentUser({ dossier: updatedDossier });
    setEditingIndex(null);
    setEditingText('');
  };
  // ─────────────────────────────────────────────────────────────

  const handleItemPress4a = (item: any) => {
    const entry8 = fichier_8a.find(e => e.id === item.id_8a);
    if (!entry8) return;
    const href = entry8.href;
    if (href.startsWith('popup:')) {
      setShowSection(href.replace('popup:', ''));
      setShowSectionLabel(item.label);
      setCurrentSectionKey(entry8.sectionkey);
      setHideDateInSection(item.information === 'nodate');
      return;
    }
    setId4a(item.id);
    setId3a(item.id_3a !== '.' ? Number(item.id_3a) : undefined);
    router.push({ pathname: href, params: { id_4a: item.id } });
  };

  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 renderItemSection = (items: any[]) =>
    (items ?? []).slice().reverse().map((item, displayIndex) => {
      // Les items sont affichés en ordre inversé → on retrouve l'index réel
      const actualIndex = items.length - 1 - displayIndex;
      return (
        <View key={displayIndex} style={styles.remarkItem}>

          {/* Contenu texte + date */}
          <View style={{ flexDirection: 'column', flex: 1 }}>
            {!hideDateInSection && (
              <AppText style={styles.dateText} text={formatDateOnly(item.date)} />
            )}
            <AppText style={styles.remarkText} text={item.text} />
          </View>

          {/* Bouton édition (écrou) */}
          <TouchableOpacity
            onPress={() => {
              setEditingIndex(actualIndex);
              setEditingText(item.text ?? '');
            }}
            style={styles.editButton}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
          >
            <AntDesign name="setting" size={18} color="#999" />
          </TouchableOpacity>

          <YesNoDossierPopUp
            message={'Ajouter ?'}
            visible={isV}
            onCloseGoHome={() => { setIsV(false); setShowSection(null); router.push('/'); }}
            onClose={() => setIsV(false)}
          />
        </View>
      );
    });

  const onClosePage = () => router.push('/');

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={[styles.popV2, { width: Dimensions.get('window').width, height: Dimensions.get('window').height }]}>

        {!showSection ? (
          <View style={{ flex: 1 }}>
            <ScrollView
              style={{ flex: 1 }}
              contentContainerStyle={styles.buttonsList}
              showsVerticalScrollIndicator={false}
            >
              {buttons.map((btn, index) => (
                <TouchableOpacity
                  key={index}
                  onPress={() => handleItemPress4a(btn)}
                  style={styles.leftButton}
                  activeOpacity={0.7}
                >
                  <AppText
                    text={btn.label}
                    color={colors.black}
                    style={styles.leftButtonText}
                  />
                </TouchableOpacity>
              ))}
            </ScrollView>
            <View style={styles.closeButtonWrapper}>
              <Button text="Fermer" onPress={onClosePage} isSelected />
            </View>
          </View>
        ) : (
          <View style={{ flex: 1, width: '100%' }}>
            <AppText
              text={showSectionLabel ?? ''}
              style={{ textAlign: 'center', marginTop: 20, fontSize: 25, fontWeight: '700' }}
            />
            <ScrollView style={{ flex: 1 }} contentContainerStyle={{ paddingTop: 20, paddingBottom: 5 }}>
              {renderItemSection(currentSectionItems)}
            </ScrollView>
            <View style={styles.centeredContainer}>
              <Button text="Retour" onPress={() => setShowSection(null)} />
              <Button
                text="Ajouter"
                isSelected
                onPress={() => setIsPopupVisible(true)}
              />
            </View>
          </View>
        )}

        <RemarquePopup
          visible={isPopupVisible}
          onClose={() => setIsPopupVisible(false)}
          sectionKey={
            currentSectionKey === 'carnetdebord'
              ? 'Carnet de bord'
              : currentSectionKey
          }
          sectionLabel={showSectionLabel}
        />

      </View>

      {/* ── Modal d'édition d'une entrée ───────────────────────── */}
      <Modal
        visible={editingIndex !== null}
        transparent
        animationType="fade"
        onRequestClose={() => setEditingIndex(null)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalCard}>
            <AppText
              text="Modifier l'entrée"
              style={{ fontWeight: '700', fontSize: 18, marginBottom: 14, textAlign: 'center' }}
            />
            <TextInput
              value={editingText}
              onChangeText={setEditingText}
              multiline
              style={styles.editInput}
              autoFocus
            />
            <View style={styles.modalButtons}>
              <Button text="Annuler" onPress={() => { setEditingIndex(null); setEditingText(''); }} />
              <Button text="Sauvegarder" isSelected onPress={handleSaveEdit} />
            </View>
          </View>
        </View>
      </Modal>
      {/* ─────────────────────────────────────────────────────── */}

    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  popV2: {
    backgroundColor: 'white',
    padding: 20,
    flex: 1,
  },
  buttonsList: {
    alignItems: 'flex-start',
    paddingTop: 8,
    paddingBottom: 8,
  },
  leftButton: {
    backgroundColor: 'white',
    borderRadius: layout.buttons.borderRadius,
    paddingHorizontal: layout.padding,
    paddingVertical: layout.padding / 2,
    marginVertical: 2,
  },
  leftButtonText: {
    fontWeight: 'bold',
    fontStyle: 'italic',
  },
  closeButtonWrapper: {
    paddingVertical: 14,
    alignItems: 'center',
    borderTopWidth: 1,
    borderTopColor: '#eee',
    marginTop: 8,
  },
  centeredContainer: {
    paddingVertical: 20,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 10,
  },
  dateText: {
    fontSize: 14,
    fontWeight: '700',
    marginBottom: 2,
  },
  remarkItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 5,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#ccc',
  },
  remarkText: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  editButton: {
    marginLeft: 10,
    padding: 4,
  },
  // ── Styles modal édition ──────────────────────────────────────
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalCard: {
    backgroundColor: 'white',
    borderRadius: 12,
    padding: 24,
    width: '85%',
  },
  editInput: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 10,
    minHeight: 90,
    textAlignVertical: 'top',
    fontSize: 14,
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 12,
    marginTop: 16,
  },
});

export default DossierPage;