// app/(Professor)/SumariosAlunos.tsx
import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  ActivityIndicator,
  Animated,
  FlatList,
  Modal,
  RefreshControl,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { supabase } from '../../../lib/supabase';
import { useTheme } from '../../../themecontext';

// --- INTERFACES ---
export interface Aluno {
  id: string;
  nome: string;
  n_escola: string;
  turma: string;
}

interface Sumario {
  id: string;
  data: string;
  sumario: string;
}

const SumariosAlunos = memo(() => {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const params = useLocalSearchParams();
  const insets = useSafeAreaInsets();

  const [search, setSearch] = useState('');
  const [turmas, setTurmas] = useState<{ nome: string; alunos: Aluno[] }[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  // Estados do Modal e Avisos
  const [modalVisible, setModalVisible] = useState(false);
  const [alunoSelecionado, setAlunoSelecionado] = useState<Aluno | null>(null);
  const [sumarios, setSumarios] = useState<Sumario[]>([]);
  const [loadingSumarios, setLoadingSumarios] = useState(false);

  const [toast, setToast] = useState<{ visible: boolean; message: string; type: 'error' | 'success' | 'info' }>({ visible: false, message: '', type: 'info' });
  const slideAnim = useRef(new Animated.Value(-100)).current;

  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';
  const erroCor = '#EF4444';
  const sucessoCor = '#10B981';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#F4F7FA', 
    card: isDarkMode ? '#161618' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    secundario: isDarkMode ? '#94A3B8' : '#64748B',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : '#E0F2F4',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    vermelho: erroCor,
    verde: sucessoCor,
  }), [isDarkMode]);

  const showToast = useCallback((message: string, type: 'error' | 'success' | 'info' = 'info') => {
    setToast({ visible: true, message, type });
    Animated.timing(slideAnim, { toValue: insets.top + 10, duration: 300, useNativeDriver: true }).start(() => {
      setTimeout(() => {
        Animated.timing(slideAnim, { toValue: -100, duration: 300, useNativeDriver: true })
          .start(() => setToast({ visible: false, message: '', type: 'info' }));
      }, 3500);
    });
  }, [insets.top, slideAnim]);

  const fetchAlunos = async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('alunos')
        .select('id, nome, n_escola, ano, turma_curso')
        .order('ano', { ascending: false })
        .order('nome', { ascending: true });

      if (error) throw error;

      const agrupadas: Record<string, Aluno[]> = {};
      data?.forEach(item => {
        const nomeTurma = `${item.ano}º ${item.turma_curso}`.trim().toUpperCase();
        if (!agrupadas[nomeTurma]) agrupadas[nomeTurma] = [];
        agrupadas[nomeTurma].push({
          id: item.id,
          nome: item.nome,
          n_escola: item.n_escola,
          turma: nomeTurma,
        });
      });

      setTurmas(Object.keys(agrupadas)
        .sort((a, b) => b.localeCompare(a))
        .map(nome => ({ nome, alunos: agrupadas[nome] }))
      );
    } catch (err) {
      console.error(err);
      showToast("Erro ao carregar as turmas.", "error");
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const abrirSumarios = async (aluno: Aluno) => {
    setAlunoSelecionado(aluno);
    setModalVisible(true);
    setLoadingSumarios(true);
    try {
      const hoje = new Date().toISOString().split('T')[0];
      const { data: listaEstagios } = await supabase
        .from('estagios')
        .select('data_inicio, data_fim')
        .lte('data_inicio', hoje)
        .gte('data_fim', hoje)
        .limit(1);

      let inicio = '2026-01-01';
      let fim = '2026-12-31';

      if (listaEstagios && listaEstagios.length > 0) {
        inicio = listaEstagios[0].data_inicio;
        fim = listaEstagios[0].data_fim;
      }

      const { data, error } = await supabase
        .from('presencas')
        .select('id, data, sumario')
        .eq('aluno_id', aluno.id)
        .gte('data', inicio)
        .lte('data', fim)
        .not('sumario', 'is', null)
        .order('data', { ascending: false });

      if (error) throw error;
      setSumarios(data || []);
      
    } catch (err) {
      console.error(err);
      showToast("Erro ao carregar o caderno.", "error");
    } finally {
      setLoadingSumarios(false);
    }
  };

  useEffect(() => { fetchAlunos(); }, []);

  useEffect(() => {
    if (params.alunoId && typeof params.alunoId === 'string' && !modalVisible) {
      abrirSumarios({ id: params.alunoId, nome: (params.nome as string) || 'Aluno', n_escola: '', turma: '' });
    }
  }, [params.alunoId]);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    fetchAlunos();
  }, []);

  const filteredTurmas = useMemo(() => {
    return turmas
      .map(turma => ({
        ...turma,
        alunos: turma.alunos.filter(a =>
          a.nome.toLowerCase().includes(search.toLowerCase()) || a.n_escola.includes(search)
        ),
      }))
      .filter(t => t.alunos.length > 0);
  }, [turmas, search]);

  return (
    <View style={{ flex: 1, backgroundColor: cores.fundo }}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} translucent backgroundColor="transparent" />
      
      {/* 🟢 TOAST ANIMADO NO TOPO */}
      <Animated.View style={[
        styles.toastContainer, 
        { transform: [{ translateY: slideAnim }] },
        toast.type === 'error' ? { backgroundColor: cores.vermelho } : 
        toast.type === 'success' ? { backgroundColor: cores.verde } : 
        { backgroundColor: cores.azul }
      ]}>
        <Ionicons 
          name={toast.type === 'error' ? "warning" : toast.type === 'success' ? "checkmark-circle" : "information-circle"} 
          size={24} 
          color="#FFF" 
        />
        <Text style={styles.toastText}>{toast.message}</Text>
      </Animated.View>

      <SafeAreaView style={styles.safe} edges={['top', 'left', 'right']}>
        
        {/* HEADER MODERNO */}
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.btnAction, { borderColor: cores.borda, backgroundColor: cores.card }]} 
            onPress={() => router.back()}
          >
            <Ionicons name="chevron-back" size={24} color={cores.azul} />
          </TouchableOpacity>
          
          <View style={{ alignItems: 'center' }}>
            <Text style={[styles.headerTitle, { color: cores.texto }]}>Sumários</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>Estágios+</Text>
          </View>

          <TouchableOpacity 
            style={[styles.btnAction, { borderColor: cores.borda, backgroundColor: cores.card }]} 
            onPress={fetchAlunos}
          >
            <Ionicons name="reload-outline" size={20} color={cores.azul} />
          </TouchableOpacity>
        </View>

        {/* SEARCH SECTION MODERNA */}
        <View style={styles.searchSection}>
          <View style={[styles.searchBar, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <Ionicons name="search-outline" size={20} color={cores.secundario} style={{ marginRight: 10 }} />
            <TextInput
              style={[styles.searchInput, { color: cores.texto }]}
              placeholder="Pesquisar por nome ou nº..."
              placeholderTextColor={cores.secundario}
              value={search}
              onChangeText={setSearch}
            />
          </View>
        </View>

        {loading && !refreshing ? (
          <ActivityIndicator size="large" color={cores.azul} style={{ marginTop: 50 }} />
        ) : (
          <FlatList
            data={filteredTurmas}
            keyExtractor={item => item.nome}
            contentContainerStyle={[styles.listPadding, { paddingBottom: insets.bottom + 20 }]}
            showsVerticalScrollIndicator={false}
            refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={cores.azul} />}
            renderItem={({ item }) => (
              <View style={{ marginBottom: 30 }}>
                
                <View style={styles.sectionHeader}>
                  <View style={[styles.sectionDot, { backgroundColor: cores.laranja }]} />
                  <Text style={[styles.sectionTitle, { color: cores.texto }]}>{item.nome}</Text>
                  <View style={[styles.sectionLine, { backgroundColor: cores.borda }]} />
                </View>

                {item.alunos.map((aluno) => (
                  <TouchableOpacity
                    key={aluno.id}
                    activeOpacity={0.7}
                    style={[styles.alunoCard, { backgroundColor: cores.card, borderColor: cores.borda }]}
                    onPress={() => abrirSumarios(aluno)}
                  >
                    <View style={[styles.avatar, { backgroundColor: cores.azulSuave }]}>
                        <Text style={[styles.avatarText, { color: cores.azul }]}>
                            {aluno.nome.charAt(0).toUpperCase()}
                        </Text>
                    </View>
                    
                    <View style={styles.alunoInfo}>
                      <Text style={[styles.alunoNome, { color: cores.texto }]} numberOfLines={1}>{aluno.nome}</Text>
                      <View style={styles.idRow}>
                        <Ionicons name="book-outline" size={14} color={cores.secundario} />
                        <Text style={[styles.idText, { color: cores.secundario }]}>Nº {aluno.n_escola} • Ver Caderno</Text>
                      </View>
                    </View>

                    <View style={[styles.statusBadge, { backgroundColor: cores.fundo, borderColor: cores.borda }]}>
                         <Ionicons name="chevron-forward" size={18} color={cores.secundario} />
                    </View>
                  </TouchableOpacity>
                ))}
              </View>
            )}
            ListEmptyComponent={() => (
              <View style={styles.emptyContainer}>
                <View style={[styles.emptyIconCircle, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="people-outline" size={40} color={cores.azul} />
                </View>
                <Text style={[styles.emptyText, { color: cores.secundario }]}>Nenhum aluno encontrado.</Text>
              </View>
            )}
          />
        )}

        {/* MODAL DE SUMÁRIOS */}
        <Modal visible={modalVisible} animationType="slide" transparent onRequestClose={() => setModalVisible(false)}>
          <View style={styles.modalOverlay}>
            <View style={[styles.modalContent, { backgroundColor: cores.fundo }]}>
              
              <View style={[styles.modalHeader, { borderBottomColor: cores.borda }]}>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.modalTitle, { color: cores.texto }]}>Caderno Diário</Text>
                  <Text style={[styles.modalSubtitle, { color: cores.laranja }]} numberOfLines={1}>{alunoSelecionado?.nome}</Text>
                </View>
                <TouchableOpacity onPress={() => setModalVisible(false)} style={[styles.closeBtn, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="close" size={24} color={cores.azul} />
                </TouchableOpacity>
              </View>

              {loadingSumarios ? (
                <ActivityIndicator style={{ marginTop: 50 }} color={cores.azul} size="large" />
              ) : (
                <ScrollView contentContainerStyle={{ padding: 20, paddingBottom: insets.bottom + 60 }} showsVerticalScrollIndicator={false}>
                  {sumarios.length === 0 ? (
                    <View style={[styles.emptyContainer, { marginTop: 60 }]}>
                      <View style={[styles.emptyIconCircle, { backgroundColor: cores.azulSuave }]}>
                        <Ionicons name="document-text-outline" size={40} color={cores.azul} />
                      </View>
                      <Text style={[styles.emptyText, { color: cores.secundario }]}>Sem sumários registados.</Text>
                      <Text style={[styles.emptySubText, { color: cores.secundario, opacity: 0.7 }]}>Os diários de bordo irão aparecer aqui.</Text>
                    </View>
                  ) : (
                    sumarios.map((s) => (
                      <View key={s.id} style={[styles.sumarioCard, { backgroundColor: cores.card, borderColor: cores.borda }]}>
                        <View style={styles.sumarioTop}>
                           <View style={[styles.dateTag, { backgroundColor: cores.azulSuave }]}>
                              <Ionicons name="calendar-outline" size={14} color={cores.azul} />
                              <Text style={[styles.dateTagText, { color: cores.azul }]}>
                                {new Date(s.data).toLocaleDateString('pt-PT', { day: '2-digit', month: 'short' })}
                              </Text>
                           </View>
                           <View style={[styles.dotLine, { backgroundColor: cores.borda }]} />
                        </View>
                        <Text style={[styles.sumarioTexto, { color: cores.texto }]}>{s.sumario}</Text>
                      </View>
                    ))
                  )}
                </ScrollView>
              )}
            </View>
          </View>
        </Modal>

      </SafeAreaView>
    </View>
  );
});

const styles = StyleSheet.create({
  safe: { flex: 1 },
  // TOAST STYLES
  toastContainer: { position: 'absolute', left: 20, right: 20, zIndex: 1000, flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 16, elevation: 6, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.2, shadowRadius: 8 },
  toastText: { color: '#FFF', fontSize: 14, fontWeight: '700', marginLeft: 12, flex: 1 },

  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 15 },
  headerTitle: { fontSize: 20, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  
  searchSection: { paddingHorizontal: 20, marginBottom: 15 },
  searchBar: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, borderRadius: 18, borderWidth: 1.5 },
  searchInput: { flex: 1, fontSize: 15, fontWeight: '600' },
  
  listPadding: { paddingHorizontal: 20, paddingTop: 10 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 20, marginTop: 10 },
  sectionDot: { width: 8, height: 8, borderRadius: 4, marginRight: 10 },
  sectionTitle: { fontSize: 14, fontWeight: '900', letterSpacing: 0.5 },
  sectionLine: { flex: 1, height: 1.5, marginLeft: 15, opacity: 0.6 },
  
  alunoCard: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 24, marginBottom: 12, borderWidth: 1, elevation: 2, shadowColor: '#000', shadowOpacity: 0.03, shadowRadius: 8, shadowOffset: { width: 0, height: 2 } },
  avatar: { width: 50, height: 50, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  avatarText: { fontSize: 20, fontWeight: '900' },
  alunoInfo: { flex: 1, marginLeft: 15, paddingRight: 10 },
  alunoNome: { fontSize: 16, fontWeight: '800', letterSpacing: -0.3, marginBottom: 4 },
  idRow: { flexDirection: 'row', alignItems: 'center', gap: 5 },
  idText: { fontSize: 12, fontWeight: '700' },
  statusBadge: { width: 36, height: 36, borderRadius: 12, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  
  modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'flex-end' },
  modalContent: { height: '88%', borderTopLeftRadius: 32, borderTopRightRadius: 32, overflow: 'hidden' },
  modalHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 20, paddingBottom: 15, borderBottomWidth: 1 },
  modalTitle: { fontSize: 22, fontWeight: '900', letterSpacing: -0.5 },
  modalSubtitle: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 4 },
  closeBtn: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  
  sumarioCard: { padding: 20, borderRadius: 24, marginBottom: 16, borderWidth: 1, elevation: 1, shadowColor: '#000', shadowOpacity: 0.02, shadowRadius: 5 },
  sumarioTop: { flexDirection: 'row', alignItems: 'center', marginBottom: 16 },
  dateTag: { flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 12, paddingVertical: 6, borderRadius: 12 },
  dateTagText: { fontSize: 12, fontWeight: '900', textTransform: 'uppercase' },
  dotLine: { flex: 1, height: 1.5, marginLeft: 12, opacity: 0.4 },
  sumarioTexto: { fontSize: 15, lineHeight: 24, fontWeight: '600' },
  
  emptyContainer: { marginTop: 100, alignItems: 'center' },
  emptyIconCircle: { width: 80, height: 80, borderRadius: 40, justifyContent: 'center', alignItems: 'center', marginBottom: 15 },
  emptyText: { fontSize: 15, fontWeight: '700' },
  emptySubText: { fontSize: 13, fontWeight: '600', marginTop: 4 }
});

export default SumariosAlunos;