// app/Professor/Alunos/Faltas.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Linking,
  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 Falta {
  id: string;
  data: string;
  justificacao_url: string | null;
  estado: string;
}

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

  // Estados da Lista
  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 de Faltas
  const [modalVisible, setModalVisible] = useState(false);
  const [alunoSelecionado, setAlunoSelecionado] = useState<Aluno | null>(null);
  const [faltas, setFaltas] = useState<Falta[]>([]);
  const [loadingFaltas, setLoadingFaltas] = 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',
    vermelho: '#EF4444',
    vermelhoSuave: isDarkMode ? 'rgba(239, 68, 68, 0.12)' : '#FEF2F2',
    verde: '#10B981',
  }), [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 abrirFaltas = async (aluno: Aluno) => {
    setAlunoSelecionado(aluno);
    setModalVisible(true);
    setLoadingFaltas(true);
    setFaltas([]);

    try {
      // 1. Procurar o estágio ativo/recente do aluno para obter as datas
      const { data: estagioData, error: errEstagio } = await supabase
        .from('estagios')
        .select('data_inicio, data_fim')
        .eq('aluno_id', aluno.id)
        .order('data_inicio', { ascending: false })
        .limit(1)
        .maybeSingle();

      if (errEstagio) throw errEstagio;

      // Se não houver estágio, não há intervalo para filtrar, logo não mostramos faltas "soltas"
      if (!estagioData) {
        setFaltas([]);
        return;
      }

      // 2. Buscar presenças com estado 'faltou' APENAS dentro das datas do estágio
      const { data, error } = await supabase
        .from('presencas')
        .select('id, data, justificacao_url, estado')
        .eq('aluno_id', aluno.id)
        .eq('estado', 'faltou')
        .gte('data', estagioData.data_inicio)
        .lte('data', estagioData.data_fim)
        .order('data', { ascending: false });

      if (error) throw error;
      setFaltas(data || []);
    } catch (err) {
      console.error(err);
      Alert.alert("Erro", "Falha ao carregar o histórico de faltas do estágio.");
    } finally {
      setLoadingFaltas(false);
    }
  };

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

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

  const verDocumento = async (url: string) => {
    try {
      await Linking.openURL(url);
    } catch (error) {
      Alert.alert("Erro", "Não foi possível abrir o ficheiro.");
    }
  };

  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 }]}>Faltas</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>Histórico de Assiduidade</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 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 }]}
            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={() => abrirFaltas(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="finger-print-outline" size={13} color={cores.secundario} />
                        <Text style={[styles.idText, { color: cores.secundario }]}>Nº {aluno.n_escola}</Text>
                      </View>
                    </View>

                    <View style={[styles.statusBadge, { backgroundColor: cores.vermelhoSuave }]}>
                         <Ionicons name="warning-outline" size={12} color={cores.vermelho} />
                         <Text style={[styles.statusText, { color: cores.vermelho }]}>VER FALTAS</Text>
                    </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' }}>Nenhum aluno encontrado.</Text>
              </View>
            )}
          />
        )}

        {/* MODAL DE DETALHES DE FALTAS */}
        <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 }]}>Registo de Faltas</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>

              {loadingFaltas ? (
                <ActivityIndicator style={{ marginTop: 50 }} color={cores.azul} />
              ) : (
                <ScrollView contentContainerStyle={{ padding: 24 }} showsVerticalScrollIndicator={false}>
                  {faltas.length === 0 ? (
                    <View style={styles.emptyContainer}>
                      <Ionicons name="happy-outline" size={60} color={cores.borda} />
                      <Text style={{ color: cores.secundario, marginTop: 10, fontWeight: '700' }}>Este aluno não tem faltas no estágio atual!</Text>
                    </View>
                  ) : (
                    faltas.map((f) => (
                      <View key={f.id} style={[styles.faltaCard, { backgroundColor: cores.card, borderColor: cores.borda }]}>
                        <View style={[styles.dateIcon, { backgroundColor: cores.azulSuave }]}>
                          <Ionicons name="calendar-outline" size={20} color={cores.azul} />
                        </View>
                        <View style={{ flex: 1, marginLeft: 15 }}>
                          <Text style={[styles.faltaData, { color: cores.texto }]}>
                            {new Date(f.data).toLocaleDateString('pt-PT', { day: '2-digit', month: 'long', year: 'numeric' })}
                          </Text>
                          <Text style={[styles.statusFaltaText, { color: f.justificacao_url ? cores.verde : cores.vermelho }]}>
                            {f.justificacao_url ? 'JUSTIFICADA' : 'INJUSTIFICADA'}
                          </Text>
                        </View>
                        {f.justificacao_url && (
                          <TouchableOpacity style={[styles.btnView, { backgroundColor: cores.azul }]} onPress={() => verDocumento(f.justificacao_url!)}>
                            <Ionicons name="eye-outline" size={18} color="#fff" />
                          </TouchableOpacity>
                        )}
                      </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', marginTop: 10, 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: 48, height: 48, borderRadius: 16, justifyContent: 'center', alignItems: 'center' },
  avatarText: { fontSize: 18, 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: { flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 8, paddingVertical: 4, borderRadius: 10 },
  statusText: { fontSize: 9, fontWeight: '900' },
  emptyContainer: { marginTop: 80, alignItems: 'center' },
  modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'flex-end' },
  modalContent: { height: '85%', borderTopLeftRadius: 40, borderTopRightRadius: 40, elevation: 20 },
  modalHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 24 },
  modalTitle: { fontSize: 20, fontWeight: '900' },
  modalSubtitle: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', marginTop: 2 },
  closeBtn: { width: 40, height: 40, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  faltaCard: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 24, marginBottom: 12, borderWidth: 1 },
  dateIcon: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  faltaData: { fontSize: 16, fontWeight: '800' },
  statusFaltaText: { fontSize: 10, fontWeight: '900', marginTop: 2 },
  btnView: { width: 40, height: 40, borderRadius: 12, justifyContent: 'center', alignItems: 'center' }
});

export default ListaFaltasProfessor;