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

// --- 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
  const [modalVisible, setModalVisible] = useState(false);
  const [alunoSelecionado, setAlunoSelecionado] = useState<Aluno | null>(null);
  const [sumarios, setSumarios] = useState<Sumario[]>([]);
  const [loadingSumarios, setLoadingSumarios] = useState(false);

  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#FFFFFF',
    card: isDarkMode ? '#161618' : '#F8FAFC',
    texto: isDarkMode ? '#F8FAFC' : '#1A365D',
    secundario: isDarkMode ? '#94A3B8' : '#718096',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.12)' : '#F0F9FA',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
  }), [isDarkMode]);

  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);
    } 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);
    } finally {
      setLoadingSumarios(false);
    }
  };

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

  // Abre automaticamente se vier de outra página com params
  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'} />
      <SafeAreaView style={styles.safe} edges={['top']}>
        
        {/* HEADER */}
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.btnAction, { borderColor: cores.borda }]} 
            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 }]}>Caderno de Registos</Text>
          </View>

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

        {/* SEARCH */}
        <View style={styles.searchSection}>
          <View style={[styles.searchBar, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <Ionicons name="search-outline" size={20} color={cores.azul} />
            <TextInput
              style={[styles.searchInput, { color: cores.texto }]}
              placeholder="Pesquisar aluno..."
              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 }]}
            refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={cores.azul} />}
            renderItem={({ item }) => (
              <View style={{ marginBottom: 25 }}>
                <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.8}
                    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 }]}>{aluno.nome}</Text>
                      <View style={styles.idRow}>
                        <Ionicons name="book-outline" size={13} 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.azulSuave }]}>
                         <Ionicons name="chevron-forward" size={14} color={cores.azul} />
                    </View>
                  </TouchableOpacity>
                ))}
              </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, { borderBottomWidth: 1, borderBottomColor: cores.borda }]}>
                <View>
                  <Text style={[styles.modalTitle, { color: cores.texto }]}>Caderno de Sumários</Text>
                  <Text style={[styles.modalSubtitle, { color: cores.laranja }]}>{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} />
              ) : (
                <ScrollView contentContainerStyle={{ padding: 24, paddingBottom: 60 }} showsVerticalScrollIndicator={false}>
                  {sumarios.length === 0 ? (
                    <View style={styles.emptyContainer}>
                      <Ionicons name="document-text-outline" size={60} color={cores.borda} />
                      <Text style={{ color: cores.secundario, marginTop: 10, fontWeight: '700' }}>Sem sumários registados.</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={12} 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 },
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 24, paddingVertical: 15 },
  headerTitle: { fontSize: 22, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  searchSection: { paddingHorizontal: 24, marginBottom: 10 },
  searchBar: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, borderRadius: 20, borderWidth: 1.5 },
  searchInput: { flex: 1, marginLeft: 12, fontSize: 14, fontWeight: '700' },
  listPadding: { paddingHorizontal: 24, paddingTop: 10 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 18, marginTop: 10 },
  sectionDot: { width: 8, height: 8, borderRadius: 4, marginRight: 10 },
  sectionTitle: { fontSize: 13, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 0.8 },
  sectionLine: { flex: 1, height: 1, marginLeft: 15, opacity: 0.5 },
  alunoCard: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 28, marginBottom: 12, borderWidth: 1, elevation: 3, shadowColor: '#000', shadowOpacity: 0.04, shadowRadius: 10 },
  avatar: { width: 48, height: 48, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  avatarText: { fontSize: 18, fontWeight: '900' },
  alunoInfo: { flex: 1, marginLeft: 15 },
  alunoNome: { fontSize: 16, fontWeight: '800' },
  idRow: { flexDirection: 'row', alignItems: 'center', gap: 5, marginTop: 3 },
  idText: { fontSize: 12, fontWeight: '600' },
  statusBadge: { width: 32, height: 32, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'flex-end' },
  modalContent: { height: '85%', borderTopLeftRadius: 40, borderTopRightRadius: 40 },
  modalHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 24 },
  modalTitle: { fontSize: 20, fontWeight: '900' },
  modalSubtitle: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase' },
  closeBtn: { width: 40, height: 40, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  sumarioCard: { padding: 20, borderRadius: 24, marginBottom: 16, borderWidth: 1 },
  sumarioTop: { flexDirection: 'row', alignItems: 'center', marginBottom: 12 },
  dateTag: { flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 10, paddingVertical: 5, borderRadius: 10 },
  dateTagText: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase' },
  dotLine: { flex: 1, height: 1, marginLeft: 12, opacity: 0.3 },
  sumarioTexto: { fontSize: 15, lineHeight: 22, fontWeight: '600' },
  emptyContainer: { marginTop: 80, alignItems: 'center' },
});

export default SumariosAlunos;