// app/(Professor)/Presencas.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  FlatList,
  RefreshControl,
  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;
}

const Presencas = memo(() => {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  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);

  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('Erro ao buscar alunos:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  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 EPVC */}
        <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 }]}>Presenças</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>Controlo Diário</Text>
          </View>

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

        {/* SEARCH BAR */}
        <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="Procurar 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 }}>
                {/* SEPARADOR DE TURMA */}
                <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={() =>
                        router.push({
                          pathname: '/Professor/Alunos/CalendarioPresencas',
                          params: { alunoId: aluno.id, nome: aluno.nome },
                        })
                    }
                  >
                    <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="calendar-outline" size={13} color={cores.secundario} />
                        <Text style={[styles.idText, { color: cores.secundario }]}>Abrir Calendário</Text>
                      </View>
                    </View>

                    <View style={[styles.statusBadge, { backgroundColor: cores.azulSuave }]}>
                         <Ionicons name="chevron-forward" size={16} color={cores.azul} />
                    </View>
                  </TouchableOpacity>
                ))}
              </View>
            )}
            ListEmptyComponent={() => (
              <View style={styles.emptyContainer}>
                <Ionicons name="people-outline" size={60} color={cores.borda} />
                <Text style={{ color: cores.secundario, marginTop: 10, fontWeight: '700' }}>Sem resultados.</Text>
              </View>
            )}
          />
        )}
      </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 },
  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: 50, height: 50, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  avatarText: { fontSize: 20, fontWeight: '900' },
  alunoInfo: { flex: 1, marginLeft: 15 },
  alunoNome: { fontSize: 16, fontWeight: '800', letterSpacing: -0.3 },
  idRow: { flexDirection: 'row', alignItems: 'center', gap: 5, marginTop: 3 },
  idText: { fontSize: 13, fontWeight: '600' },
  statusBadge: { width: 34, height: 34, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  emptyContainer: { marginTop: 100, alignItems: 'center' },
});

export default Presencas;