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

  // Estados para o Toast
  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', // Novo design
    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,
    vermelhoSuave: isDarkMode ? 'rgba(239, 68, 68, 0.15)' : '#FEE2E2',
    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("Erro ao carregar lista:", err);
      showToast("Falha ao carregar a lista de alunos.", "error");
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

      const { data, error } = await supabase
        .from('profiles')
        .delete()
        .eq('id', alunoParaEliminar.id)
        .select();

      if (error) throw error;

      if (!data || data.length === 0) {
        throw new Error("O servidor recusou a eliminação. Verifique permissões RLS.");
      }

      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);
      showToast("Aluno apagado com sucesso do sistema.", "success");

    } catch (err: any) {
      console.error("ERRO AO APAGAR:", err);
      showToast(err.message || "Não foi possível apagar o aluno.", "error");
    } 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'} 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 }]}>Lista de alunos</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>

        {/* PESQUISA */}
        <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="Procurar 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 + 40 }]}
            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={() => 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 }]} numberOfLines={1}>{aluno.nome}</Text>
                      <View style={{ flexDirection: 'row', alignItems: 'center', gap: 5 }}>
                        <Ionicons name="id-card-outline" size={14} color={cores.secundario} />
                        <Text style={[styles.idText, { color: cores.secundario }]}>Nº {aluno.n_escola}</Text>
                      </View>
                    </View>
                    <TouchableOpacity 
                      style={styles.trashBtn}
                      onPress={() => {
                        setAlunoParaEliminar(aluno);
                        setShowDeleteModal(true);
                      }}
                    >
                      <Ionicons name="trash-outline" size={20} color={cores.vermelho} style={{ opacity: 0.7 }} />
                    </TouchableOpacity>
                  </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 ELIMINAÇÃO */}
        <Modal visible={showDeleteModal} transparent animationType="fade">
          <View style={styles.modalOverlay}>
            <View style={[styles.modalCard, { backgroundColor: cores.card }]}>
              <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 }]}>Ação Irreversível</Text>
              <Text style={[styles.modalDesc, { color: cores.secundario }]}>
                Tens a certeza que queres eliminar o registo de <Text style={{fontWeight:'900', color: cores.texto}}>{alunoParaEliminar?.nome}</Text>?
              </Text>
              <Text style={[styles.modalWarning, { color: cores.vermelho }]}>
                Isto apagará também os estágios e presenças!
              </Text>

              <View style={styles.modalButtons}>
                <TouchableOpacity 
                  style={[styles.btnModal, { borderColor: cores.borda, borderWidth: 1.5 }]} 
                  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' }]}>Sim, Apagar</Text>
                  )}
                </TouchableOpacity>
              </View>
            </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 },
  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 },
  idText: { fontSize: 13, fontWeight: '700' },
  trashBtn: { padding: 8 },

  emptyContainer: { marginTop: 100, alignItems: 'center' },
  emptyIconCircle: { width: 80, height: 80, borderRadius: 40, justifyContent: 'center', alignItems: 'center', marginBottom: 15 },
  emptyText: { fontSize: 15, fontWeight: '700' },

  modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'center', alignItems: 'center', padding: 24 },
  modalCard: { width: '100%', borderRadius: 32, padding: 24, alignItems: 'center', elevation: 10 },
  warningIconBox: { width: 70, height: 70, borderRadius: 25, justifyContent: 'center', alignItems: 'center', marginBottom: 20 },
  modalTitle: { fontSize: 22, fontWeight: '900', marginBottom: 8, textAlign: 'center', letterSpacing: -0.5 },
  modalDesc: { fontSize: 15, textAlign: 'center', lineHeight: 22, marginBottom: 10 },
  modalWarning: { fontSize: 12, fontWeight: '800', textAlign: 'center', textTransform: 'uppercase', marginBottom: 25 },
  modalButtons: { flexDirection: 'row', gap: 12, width: '100%' },
  btnModal: { flex: 1, height: 56, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  btnText: { fontSize: 15, fontWeight: '800', letterSpacing: 0.5 }
});

export default ListaAlunosProfessor;