import React from 'react';
import {
  View, Text, StyleSheet, FlatList, TouchableOpacity,
} from 'react-native';
import { useUsers } from '@/contexts/UserContext';
import { router } from 'expo-router';
import { AntDesign } from '@expo/vector-icons';
import { useAppData } from '@/contexts/AppDataContext';


const SuiviPage: React.FC = () => {
  const { fichier4a: fichier_4a, fichier8a: fichier_8a } = useAppData();
  const { currentUser } = useUsers();

  const suivis = Array.isArray(currentUser?.suivi)
    ? currentUser.suivi.filter(s => !s.ended)
    : [];

  const formatDate = (date: any): string => {
    if (!date) return '—';
    const d = new Date(date);
    if (isNaN(d.getTime())) return '—';
    return `${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')}/${d.getFullYear()}`;
  };

  // ── Lit la dernière valeur depuis globalData (où addDataToGlobal stocke tout)
  const getLatestValueFromGlobal = (symptomId: number): string => {
    if (!currentUser?.globalData) return '—';
    const entry = currentUser.globalData instanceof Map
      ? currentUser.globalData.get(symptomId)
      : currentUser.globalData?.[symptomId];
    if (!entry?.values?.length) return '—';
    const filtered = entry.values.filter(
      (v: any) => v.patient === currentUser.username || v.patient === null || v.patient === undefined
    );
    if (!filtered.length) return '—';
    const last = filtered[filtered.length - 1];
    return last.valeur !== undefined && last.valeur !== null ? String(last.valeur) : '—';
  };

  const renderSuivi = ({ item }: { item: any }) => {
    const symptoms = Array.isArray(item.symptoms) ? item.symptoms : [];

    return (
      <TouchableOpacity
        style={styles.card}
        activeOpacity={0.8}
        onPress={() => router.push({
          pathname: '/(tabs)/suivi/suivi_detail',
          params: { id_suivi: item.id },
        })}
      >
        <View style={styles.cardHeader}>
          <View style={{ flex: 1 }}>
            <Text style={styles.cardTitle}>{item.name ?? '—'}</Text>
            {item.date && (
              <Text style={styles.cardDate}>Depuis le {formatDate(item.date)}</Text>
            )}
            {item.evaluateur && (
              <Text style={styles.cardEval}>Évaluateur : {item.evaluateur}</Text>
            )}
          </View>
          <AntDesign name="right" size={18} color="#bbb" />
        </View>

        {symptoms.length > 0 && (
          <View style={styles.symptomsSection}>
            <Text style={styles.sectionLabel}>Symptômes suivis :</Text>
            {symptoms.map((s: any, idx: number) => (
              <View key={idx} style={styles.symptomRow}>
                <Text style={styles.symptomName}>{s.name ?? s.surname ?? '—'}</Text>
                <Text style={styles.symptomValue}>{getLatestValueFromGlobal(s.id)}</Text>
              </View>
            ))}
          </View>
        )}
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.container}>
      {suivis.length === 0 ? (
        <View style={styles.emptyContainer}>
          <AntDesign name="inbox" size={48} color="#ccc" />
          <Text style={styles.emptyText}>Aucun suivi actif.</Text>
        </View>
      ) : (
        <FlatList
          data={suivis}
          keyExtractor={(item, index) => `${item.id}-${index}`}
          renderItem={renderSuivi}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  listContent: { padding: 20, paddingBottom: 40 },
  emptyContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', gap: 12 },
  emptyText: { fontSize: 16, color: '#aaa', fontStyle: 'italic' },
  card: {
    backgroundColor: '#f5f5fa',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    borderWidth: 1,
    borderColor: '#eee',
    elevation: 1,
  },
  cardHeader: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: 12,
  },
  cardTitle: { fontSize: 17, fontWeight: 'bold', color: '#1a1a1a' },
  cardDate: { fontSize: 13, color: '#777', marginTop: 2 },
  cardEval: { fontSize: 12, color: '#999', marginTop: 2, fontStyle: 'italic' },
  symptomsSection: {
    borderTopWidth: 1,
    borderTopColor: '#e0e0e0',
    paddingTop: 10,
  },
  sectionLabel: { fontSize: 13, fontWeight: '600', color: '#555', marginBottom: 6 },
  symptomRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 4,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  symptomName: { fontSize: 14, color: '#333', flex: 1 },
  symptomValue: { fontSize: 14, fontWeight: 'bold', color: '#E8437B', marginLeft: 8 },
});

export default SuiviPage;