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

// --- 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);

  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 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',
    verde: '#10B981',
  }), [isDarkMode]);

  const fetchHistorico = async () => {
    try {
      setLoading(true);

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

      // 1. Procurar o estágio deste aluno
      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];

      // 2. Buscar presenças no intervalo do estágio
      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);
      Alert.alert("Erro", "Falha ao carregar dados do estágio.");
    } 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') {
      router.push({
        pathname: '/Professor/Alunos/Faltas', 
        params: { alunoId: idStr, nome: nomeStr } 
      });
    } 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'} />
      <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', flex: 1 }}>
            <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 }]} 
            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 + 20 }]}
            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);
              
              return (
                <TouchableOpacity
                  activeOpacity={0.8}
                  onPress={() => handleNavigation(item)}
                  style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}
                >
                  <View style={[styles.dateBox, { backgroundColor: cores.azulSuave }]}>
                    <Text style={[styles.dateDay, { color: cores.azul }]}>
                      {dataObj.getDate()}
                    </Text>
                    <Text style={[styles.dateMonth, { color: cores.azul }]}>
                      {dataObj.toLocaleDateString('pt-PT', { month: 'short' }).replace('.', '')}
                    </Text>
                  </View>

                  <View style={styles.infoArea}>
                    <View style={styles.statusRow}>
                      <View style={[styles.indicator, { backgroundColor: isPresente ? cores.verde : cores.vermelho }]} />
                      <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 do dia' : 'Ver 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 }]}
                      >
                        <Ionicons name="location" size={16} color={cores.azul} />
                      </TouchableOpacity>
                    )}
                    <Ionicons name="chevron-forward" size={18} color={cores.borda} />
                  </View>
                </TouchableOpacity>
              );
            }}
            ListEmptyComponent={() => (
              <View style={styles.emptyContainer}>
                <Ionicons name="calendar-outline" size={60} color={cores.borda} />
                <Text style={{ color: cores.secundario, marginTop: 10, fontWeight: '700' }}>Sem registos este ano.</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, maxWidth: 200 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  listPadding: { paddingHorizontal: 24, paddingTop: 10 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 20, marginTop: 10 },
  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 },
  card: { flexDirection: 'row', alignItems: 'center', padding: 14, borderRadius: 24, marginBottom: 12, borderWidth: 1, elevation: 2, shadowColor: '#000', shadowOpacity: 0.03, shadowRadius: 10 },
  dateBox: { width: 54, height: 54, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
  dateDay: { fontSize: 18, fontWeight: '900' },
  dateMonth: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase' },
  infoArea: { flex: 1, marginLeft: 15 },
  statusRow: { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 2 },
  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: 10 },
  iconBtn: { width: 32, height: 32, borderRadius: 10, justifyContent: 'center', alignItems: 'center' },
  emptyContainer: { marginTop: 100, alignItems: 'center' },
});

export default HistoricoPresencas;