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

interface TurmaAgrupada {
  nome: string;
  alunos: Aluno[];
}

const ListaAlunosProfessor = memo(() => {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const insets = useSafeAreaInsets();

  const [search, setSearch] = useState('');
  const [turmas, setTurmas] = useState<TurmaAgrupada[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  // Estados para o Modal de Eliminação
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [alunoParaEliminar, setAlunoParaEliminar] = useState<Aluno | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#FFFFFF',
    card: isDarkMode ? '#161618' : '#F8FAFC',
    texto: isDarkMode ? '#F8FAFC' : '#1A365D',
    secundario: isDarkMode ? '#94A3B8' : '#718096',
    azul: '#2390a6',
    laranja: '#E38E00',
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.12)' : '#F0F9FA',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    vermelho: '#EF4444',
    vermelhoSuave: isDarkMode ? 'rgba(239, 68, 68, 0.15)' : '#FEE2E2',
  }), [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 carregar lista:", err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const confirmarEliminacao = async () => {
    if (!alunoParaEliminar) return;
    
    try {
      setIsDeleting(true);

      // APAGAR NO PROFILES (O Cascade do SQL trata das tabelas 'alunos' e 'estagios')
      const { data, error } = await supabase
        .from('profiles')
        .delete()
        .eq('id', alunoParaEliminar.id)
        .select();

      if (error) throw error;

      // Se o data vier vazio, o RLS bloqueou o delete no profiles
      if (!data || data.length === 0) {
        throw new Error("O servidor recusou apagar o perfil. Verifica se as políticas RLS na tabela 'profiles' permitem DELETE.");
      }

      // Sucesso no banco -> Atualizar UI local
      setTurmas(prev => prev.map(turma => ({
        ...turma,
        alunos: turma.alunos.filter(a => a.id !== alunoParaEliminar.id)
      })).filter(t => t.alunos.length > 0));

      setShowDeleteModal(false);
      setAlunoParaEliminar(null);
      Alert.alert("Sucesso", "Aluno e todos os dados vinculados foram eliminados.");

    } catch (err: any) {
      console.error("ERRO AO APAGAR:", err);
      Alert.alert("Erro Crítico", err.message);
    } finally {
      setIsDeleting(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 */}
        <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 }]}>Alunos</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>Gestão de Turmas</Text>
          </View>
          <TouchableOpacity style={[styles.btnAction, { borderColor: cores.borda }]} onPress={fetchAlunos}>
            <Ionicons name="reload-outline" size={20} color={cores.azul} />
          </TouchableOpacity>
        </View>

        {/* PESQUISA */}
        <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 + 100 }]}
            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={() => router.push({ pathname: '/Professor/Alunos/DetalhesAluno', params: { alunoId: aluno.id } })}
                    onLongPress={() => {
                      setAlunoParaEliminar(aluno);
                      setShowDeleteModal(true);
                    }}
                  >
                    <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>
                      <Text style={[styles.idText, { color: cores.secundario }]}>Nº {aluno.n_escola}</Text>
                    </View>
                    <Ionicons name="trash-outline" size={18} color={cores.vermelho} style={{ opacity: 0.5 }} />
                  </TouchableOpacity>
                ))}
              </View>
            )}
          />
        )}

        {/* MODAL DE ELIMINAÇÃO */}
        <Modal visible={showDeleteModal} transparent animationType="fade">
          <View style={styles.modalOverlay}>
            <View style={[styles.modalCard, { backgroundColor: cores.fundo }]}>
              <View style={[styles.warningIconBox, { backgroundColor: cores.vermelhoSuave }]}>
                <Ionicons name="trash-bin-outline" size={32} color={cores.vermelho} />
              </View>
              
              <Text style={[styles.modalTitle, { color: cores.texto }]}>Eliminar Permanentemente?</Text>
              <Text style={[styles.modalDesc, { color: cores.secundario }]}>
                Estás prestes a apagar o perfil de <Text style={{fontWeight:'900', color: cores.texto}}>{alunoParaEliminar?.nome}</Text>.
                Isto removerá o acesso à app, dados escolares e estágios. **Vai dar merda** se apagares por engano!
              </Text>

              <View style={styles.modalButtons}>
                <TouchableOpacity 
                  style={[styles.btnModal, { borderColor: cores.borda, borderWidth: 1 }]} 
                  onPress={() => setShowDeleteModal(false)}
                >
                  <Text style={[styles.btnText, { color: cores.secundario }]}>Cancelar</Text>
                </TouchableOpacity>

                <TouchableOpacity 
                  style={[styles.btnModal, { backgroundColor: cores.vermelho }]} 
                  onPress={confirmarEliminacao}
                  disabled={isDeleting}
                >
                  {isDeleting ? (
                    <ActivityIndicator color="#fff" size="small" />
                  ) : (
                    <Text style={[styles.btnText, { color: '#fff' }]}>Eliminar Tudo</Text>
                  )}
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </Modal>

        {/* BOTÃO FLUTUANTE */}
        <TouchableOpacity 
          style={[styles.fab, { backgroundColor: cores.azul, bottom: insets.bottom + 20 }]} 
          onPress={() => router.push('/Professor/Alunos/CriarAluno')}
        >
          <Ionicons name="person-add" size={24} color="#fff" />
          <Text style={styles.fabText}>Novo Aluno</Text>
        </TouchableOpacity>
      </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' },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase' },
  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' },
  sectionLine: { flex: 1, height: 1, marginLeft: 15, opacity: 0.5 },
  alunoCard: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 28, marginBottom: 12, borderWidth: 1 },
  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' },
  idText: { fontSize: 13, fontWeight: '600' },
  fab: { position: 'absolute', right: 24, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 22, paddingVertical: 16, borderRadius: 22, elevation: 8, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.3, shadowRadius: 5 },
  fabText: { color: '#fff', fontSize: 15, fontWeight: '900', marginLeft: 10 },
  modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.7)', justifyContent: 'center', alignItems: 'center', padding: 30 },
  modalCard: { width: '100%', borderRadius: 32, padding: 24, alignItems: 'center' },
  warningIconBox: { width: 70, height: 70, borderRadius: 25, justifyContent: 'center', alignItems: 'center', marginBottom: 20 },
  modalTitle: { fontSize: 20, fontWeight: '900', marginBottom: 10, textAlign: 'center' },
  modalDesc: { fontSize: 15, textAlign: 'center', lineHeight: 22, marginBottom: 25 },
  modalButtons: { flexDirection: 'row', gap: 12, width: '100%' },
  btnModal: { flex: 1, height: 56, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
  btnText: { fontSize: 16, fontWeight: '800' }
});

export default ListaAlunosProfessor;