// app/Empresa/pedidos.tsx
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect } from '@react-navigation/native';
import { useRouter } from 'expo-router';
import { useCallback, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Platform,
  RefreshControl,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';
import { supabase } from '../../lib/supabase';
import { useTheme } from '../../themecontext';

export default function PedidosPendentes() {
  const { isDarkMode } = useTheme();
  const router = useRouter();

  const [pendentes, setPendentes] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const themeStyles = useMemo(() => ({
    fundo: isDarkMode ? '#0F0F0F' : '#F8FAFC',
    card: isDarkMode ? '#1A1A1A' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    textoSecundario: isDarkMode ? '#94A3B8' : '#64748B',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    azul: '#2390a6',
    laranja: '#dd8707',
    verde: '#10B981',
  }), [isDarkMode]);

  const fetchValidaçõesPendentes = async (isManualRefresh = false) => {
    if (!isManualRefresh) setLoading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

      const { data: empresa } = await supabase
        .from('empresas')
        .select('id')
        .eq('user_id', user.id)
        .single();

      if (!empresa) {
        setPendentes([]);
        return;
      }

      const { data: estagios } = await supabase
        .from('estagios')
        .select('aluno_id')
        .eq('empresa_id', empresa.id);

      if (!estagios || estagios.length === 0) {
        setPendentes([]);
        return;
      }
      
      const alunoIds = estagios.map(e => e.aluno_id);

      const { data: alunos } = await supabase
        .from('alunos')
        .select('id, nome')
        .in('id', alunoIds);

      const mapaAlunos: Record<string, string> = {};
      alunos?.forEach(a => { mapaAlunos[a.id] = a.nome; });

      // Busca presenças OU faltas que estejam pendentes de aprovação da empresa
      const { data: presencas } = await supabase
        .from('presencas')
        .select('*')
        .in('aluno_id', alunoIds)
        .eq('estado_tutor', 'pendente')
        .order('data', { ascending: false });

      const listaFormatada = presencas?.map(p => ({
        ...p,
        aluno_nome: mapaAlunos[p.aluno_id] || 'Aluno Desconhecido'
      })) || [];

      setPendentes(listaFormatada);
    } catch (error) {
      console.error(error);
      Alert.alert("Erro", "Falha ao carregar os pedidos.");
    } finally {
      if (!isManualRefresh) setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => { fetchValidaçõesPendentes(); }, []));

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    fetchValidaçõesPendentes(true);
  }, []);

  const formatarData = (dataStr: string) => {
    if (!dataStr) return '';
    const parts = dataStr.split('-');
    if (parts.length !== 3) return dataStr;
    return `${parts[2]}/${parts[1]}/${parts[0]}`; 
  };

  const getTipoInfo = (item: any) => {
      if (item.estado === 'presente') return { icone: 'checkmark-circle', cor: themeStyles.verde, texto: 'Presença e Sumário' };
      if (item.justificacao_url) return { icone: 'document-text', cor: themeStyles.laranja, texto: 'Falta com Justificação' };
      return { icone: 'close-circle', cor: themeStyles.laranja, texto: 'Falta a Confirmar' };
  };

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: themeStyles.fundo }]}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      <View style={styles.header}>
        <TouchableOpacity style={styles.btnVoltar} onPress={() => router.back()}>
          <Ionicons name="arrow-back" size={24} color={themeStyles.texto} />
        </TouchableOpacity>
        <Text style={[styles.headerTitle, { color: themeStyles.texto }]}>Pedidos</Text>
        <View style={{ width: 24 }} />
      </View>
      <View style={styles.headerTitleContainer}>
        <Text style={[styles.sectionTitle, { color: themeStyles.texto }]}>A Aguardar Validação</Text>
        <View style={[styles.badge, { backgroundColor: themeStyles.laranja + '20' }]}>
          <Text style={[styles.badgeText, { color: themeStyles.laranja }]}>{pendentes.length}</Text>
        </View>
      </View>
      {loading && !refreshing ? (
        <View style={styles.centerBox}>
          <ActivityIndicator size="large" color={themeStyles.azul} />
        </View>
      ) : (
        <ScrollView 
          contentContainerStyle={styles.scroll} 
          showsVerticalScrollIndicator={false}
          refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={[themeStyles.azul]} tintColor={themeStyles.azul} />}
        >
          {pendentes.length === 0 ? (
            <View style={[styles.emptyBox, { borderColor: themeStyles.borda, backgroundColor: themeStyles.card }]}>
              <Ionicons name="checkmark-done-circle" size={60} color={themeStyles.verde} style={{ marginBottom: 15 }} />
              <Text style={[styles.emptyTitle, { color: themeStyles.texto }]}>Tudo limpo!</Text>
              <Text style={[styles.emptyDesc, { color: themeStyles.textoSecundario }]}>
                Não tens pedidos pendentes neste momento.
              </Text>
            </View>
          ) : (
            pendentes.map((item, index) => {
              const tipo = getTipoInfo(item);
              return (
                <TouchableOpacity 
                  key={index} 
                  activeOpacity={0.7}
                  style={[styles.card, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda, borderLeftColor: tipo.cor }]}
                  onPress={() => {
                    router.push({
                      pathname: '/Empresas/validarPedido',
                      params: { 
                        aluno_id: item.aluno_id, 
                        aluno_nome: item.aluno_nome,
                        data: item.data,
                        sumario: item.sumario || '',
                        estado: item.estado,
                        justificacao_url: item.justificacao_url || ''
                      }
                    });
                  }}
                >
                  <View style={styles.cardHeader}>
                    <View style={{ flex: 1 }}>
                      <Text style={[styles.alunoName, { color: themeStyles.texto }]} numberOfLines={1}>
                        <Ionicons name="person" size={14} color={themeStyles.textoSecundario} /> {item.aluno_nome}
                      </Text>
                      <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10, marginTop: 4 }}>
                          <Text style={[styles.dataText, { color: themeStyles.textoSecundario }]}>
                            <Ionicons name="calendar-outline" size={12} /> {formatarData(item.data)}
                          </Text>
                          <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>
                              <Ionicons name={tipo.icone as any} size={14} color={tipo.cor} />
                              <Text style={{ fontSize: 12, fontWeight: '700', color: tipo.cor }}>{tipo.texto}</Text>
                          </View>
                      </View>
                    </View>
                    <Ionicons name="chevron-forward" size={24} color={themeStyles.textoSecundario} />
                  </View>
                </TouchableOpacity>
              );
            })
          )}
        </ScrollView>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0 },
  header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 20, paddingTop: 20, paddingBottom: 15 },
  btnVoltar: { padding: 5, marginLeft: -5 },
  headerTitle: { fontSize: 20, fontWeight: '900' },
  
  centerBox: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  
  headerTitleContainer: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 20, marginBottom: 20, gap: 10 },
  sectionTitle: { fontSize: 16, fontWeight: '800' },
  badge: { paddingHorizontal: 10, paddingVertical: 4, borderRadius: 12 },
  badgeText: { fontSize: 12, fontWeight: '900' },
  
  scroll: { paddingHorizontal: 20, paddingBottom: 40 },
  
  emptyBox: { alignItems: 'center', padding: 40, borderRadius: 24, borderWidth: 1, borderStyle: 'dashed', marginTop: 30 },
  emptyTitle: { fontSize: 20, fontWeight: '900', marginBottom: 8 },
  emptyDesc: { fontSize: 14, textAlign: 'center', lineHeight: 22, fontWeight: '500' },

  card: { padding: 20, borderRadius: 20, borderWidth: 1, borderLeftWidth: 5, marginBottom: 15, elevation: 1, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.03, shadowRadius: 5 },
  cardHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  alunoName: { fontSize: 17, fontWeight: '900', marginBottom: 2 },
  dataText: { fontSize: 13, fontWeight: '700' }
});