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

// --- INTERFACES ---
interface Presenca {
  id: string;
  aluno_id: string;
  data: string;
  estado: string;
  sumario: string | null;
  justificacao_url: string | null;
  created_at: string;
  lat?: number;
  lng?: number;
}

const HistoricoPresencas = memo(() => {
  const router = useRouter();
  const params = useLocalSearchParams();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets();

  const [presencas, setPresencas] = useState<Presenca[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  // ESTADOS DO 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 idStr = Array.isArray(params.alunoId) ? params.alunoId[0] : params.alunoId;
  const nomeStr = Array.isArray(params.nome) ? params.nome[0] : params.nome;

  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';
  const erroCor = '#EF4444';
  const sucessoCor = '#10B981';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#F4F7FA',
    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,
    verdeSuave: isDarkMode ? 'rgba(16, 185, 129, 0.15)' : '#DCFCE7',
  }), [isDarkMode]);

  const showToast = useCallback((message: string, type: 'error' | 'success' | 'info' = 'error') => {
    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 fetchHistorico = async () => {
    try {
      setLoading(true);

      if (!idStr) {
        console.error("ID do aluno não identificado.");
        return;
      }

      const { data: estagioData, error: errEstagio } = await supabase
        .from('estagios')
        .select('data_inicio, data_fim')
        .eq('aluno_id', idStr)
        .order('data_inicio', { ascending: false });

      if (errEstagio) throw errEstagio;

      if (!estagioData || estagioData.length === 0) {
        setPresencas([]);
        return;
      }

      const estagio = estagioData[0];

      const { data: presencasData, error: errPresencas } = await supabase
        .from('presencas')
        .select('*')
        .eq('aluno_id', idStr)
        .gte('data', estagio.data_inicio)
        .lte('data', estagio.data_fim)
        .order('data', { ascending: false });

      if (errPresencas) throw errPresencas;

      setPresencas(presencasData || []);

    } catch (error: any) {
      console.error("Erro Geral:", error);
      showToast("Falha ao carregar dados do estágio.", 'error');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => { 
    if (idStr) fetchHistorico(); 
  }, [idStr]);

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

  const handleNavigation = (item: Presenca) => {
    if (item.estado === 'faltou') {
      if (item.justificacao_url) {
        Linking.openURL(item.justificacao_url);
      } else {
        // 🟢 AVISO MODERNO USADO AQUI
        showToast("Não existe justificação anexada a esta falta.", 'info');
      }
    } else {
      router.push({
        pathname: '/Professor/Alunos/Sumarios',
        params: { alunoId: idStr, nome: nomeStr }
      });
    }
  };

  const abrirMapa = (lat: number, lng: number) => {
    const scheme = Platform.select({ ios: 'maps:0,0?q=', android: 'geo:0,0?q=' });
    const latLng = `${lat},${lng}`;
    const url = Platform.select({
      ios: `${scheme}${nomeStr}@${latLng}`,
      android: `${scheme}${latLng}(${nomeStr})`
    });
    if (url) Linking.openURL(url);
  };

  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']}>
        
        <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', flex: 1, paddingHorizontal: 10 }}>
            <Text style={[styles.headerTitle, { color: cores.texto }]}>Histórico</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]} numberOfLines={1}>
              {nomeStr}
            </Text>
          </View>

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

        {loading && !refreshing ? (
          <ActivityIndicator size="large" color={cores.azul} style={{ marginTop: 50 }} />
        ) : (
          <FlatList
            data={presencas}
            keyExtractor={(item) => item.id}
            contentContainerStyle={[styles.listPadding, { paddingBottom: insets.bottom + 40 }]}
            showsVerticalScrollIndicator={false}
            refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={cores.azul} />}
            ListHeaderComponent={() => (
              <View style={styles.sectionHeader}>
                <View style={[styles.sectionDot, { backgroundColor: cores.laranja }]} />
                <Text style={[styles.sectionTitle, { color: cores.texto }]}>Registos Recentes</Text>
                <View style={[styles.sectionLine, { backgroundColor: cores.borda }]} />
              </View>
            )}
            renderItem={({ item }) => {
              const isPresente = item.estado === 'presente';
              const dataObj = new Date(item.data);
              
              const bgColor = isPresente ? cores.verdeSuave : cores.vermelhoSuave;
              const mainColor = isPresente ? cores.verde : cores.vermelho;
              
              return (
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => handleNavigation(item)}
                  style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}
                >
                  <View style={[styles.dateBox, { backgroundColor: bgColor }]}>
                    <Text style={[styles.dateDay, { color: mainColor }]}>
                      {dataObj.getDate()}
                    </Text>
                    <Text style={[styles.dateMonth, { color: mainColor }]}>
                      {dataObj.toLocaleDateString('pt-PT', { month: 'short' }).replace('.', '')}
                    </Text>
                  </View>

                  <View style={styles.infoArea}>
                    <View style={styles.statusRow}>
                      <View style={[styles.indicator, { backgroundColor: mainColor }]} />
                      <Text style={[styles.statusText, { color: cores.texto }]}>
                        {isPresente ? 'Presença Registada' : 'Falta Marcada'}
                      </Text>
                    </View>
                    <Text style={[styles.subInfo, { color: cores.secundario }]}>
                      {isPresente 
                        ? 'Ver sumário inserido' 
                        : (item.justificacao_url ? 'Abrir justificação anexada' : 'Falta sem justificação')
                      }
                    </Text>
                  </View>

                  <View style={styles.actionIcons}>
                    {item.lat && item.lng ? (
                      <TouchableOpacity 
                        onPress={() => abrirMapa(item.lat!, item.lng!)} 
                        style={[styles.iconBtn, { backgroundColor: cores.azulSuave }]}
                        activeOpacity={0.6}
                      >
                        <Ionicons name="location" size={16} color={cores.azul} />
                      </TouchableOpacity>
                    ) : null}
                    {(!isPresente && !item.justificacao_url) ? null : (
                      <Ionicons name={isPresente ? "chevron-forward" : "document-attach"} size={20} color={cores.secundario} />
                    )}
                  </View>
                </TouchableOpacity>
              );
            }}
            ListEmptyComponent={() => (
              <View style={styles.emptyContainer}>
                <View style={[styles.emptyIconCircle, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="calendar-outline" size={40} color={cores.azul} />
                </View>
                <Text style={[styles.emptyText, { color: cores.secundario }]}>Nenhum registo efetuado.</Text>
                <Text style={[styles.emptySubText, { color: cores.secundario, opacity: 0.7 }]}>As presenças/faltas irão aparecer aqui.</Text>
              </View>
            )}
          />
        )}
      </SafeAreaView>
    </View>
  );
});

const styles = StyleSheet.create({
  safe: { flex: 1 },
  // 🟢 TOAST STYLES
  toastContainer: { position: 'absolute', left: 20, right: 20, zIndex: 100, flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 16, elevation: 5, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.2, shadowRadius: 8 },
  toastText: { color: '#FFF', fontSize: 14, fontWeight: '700', marginLeft: 10, 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 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  
  listPadding: { paddingHorizontal: 20, paddingTop: 10 },
  
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 20, marginTop: 10 },
  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 },
  
  card: { flexDirection: 'row', alignItems: 'center', padding: 14, borderRadius: 24, marginBottom: 12, borderWidth: 1, elevation: 2, shadowColor: '#000', shadowOpacity: 0.03, shadowRadius: 10, shadowOffset: { width: 0, height: 2 } },
  dateBox: { width: 56, height: 56, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
  dateDay: { fontSize: 18, fontWeight: '900' },
  dateMonth: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase' },
  
  infoArea: { flex: 1, marginLeft: 16 },
  statusRow: { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 4 },
  indicator: { width: 8, height: 8, borderRadius: 4 },
  statusText: { fontSize: 15, fontWeight: '800', letterSpacing: -0.3 },
  subInfo: { fontSize: 12, fontWeight: '600' },
  
  actionIcons: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingRight: 5 },
  iconBtn: { width: 34, height: 34, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  
  emptyContainer: { marginTop: 100, alignItems: 'center' },
  emptyIconCircle: { width: 80, height: 80, borderRadius: 40, justifyContent: 'center', alignItems: 'center', marginBottom: 15 },
  emptyText: { fontSize: 15, fontWeight: '700' },
  emptySubText: { fontSize: 13, fontWeight: '600', marginTop: 4 }
});

export default HistoricoPresencas;