// app/Empresa/alunos.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 GestaoAlunos() {
  const { isDarkMode } = useTheme();
  const router = useRouter();

  const [alunosList, setAlunosList] = 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',
    verde: '#10B981',
    laranja: '#dd8707',
  }), [isDarkMode]);

  const fetchAlunos = 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) {
        setAlunosList([]);
        return;
      }

      const { data: estagios, error } = await supabase
        .from('estagios')
        .select(`
          id,
          data_inicio,
          data_fim,
          horas_totais,
          horas_concluidas,
          alunos (id, nome)
        `)
        .eq('empresa_id', empresa.id)
        .order('data_fim', { ascending: false });

      if (error) throw error;

      const formatados = estagios?.map((estagio: any) => {
        const alunoObj = Array.isArray(estagio.alunos) ? estagio.alunos[0] : estagio.alunos;
        
        return {
          id_estagio: estagio.id,
          aluno_id: alunoObj?.id,
          aluno_nome: alunoObj?.nome || 'Aluno Desconhecido',
          data_inicio: estagio.data_inicio,
          data_fim: estagio.data_fim,
          horas_totais: estagio.horas_totais || 0,
          horas_concluidas: estagio.horas_concluidas || 0, 
        };
      }) || [];

      setAlunosList(formatados);
    } catch (error) {
      console.error(error);
      Alert.alert("Erro", "Não foi possível carregar a lista de alunos.");
    } finally {
      if (!isManualRefresh) setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => { fetchAlunos(); }, []));

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    fetchAlunos(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 getStatus = (dataFim: string) => {
    const hoje = new Date().toISOString().split('T')[0];
    if (hoje > dataFim) return { texto: 'CONCLUÍDO', cor: themeStyles.textoSecundario, bg: themeStyles.textoSecundario + '20' };
    return { texto: 'A DECORRER', cor: themeStyles.verde, bg: themeStyles.verde + '20' };
  };

  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 }]}>Os Meus Alunos</Text>
        <View style={{ width: 24 }} />
      </View>

      <View style={styles.headerTitleContainer}>
        <Text style={[styles.sectionTitle, { color: themeStyles.texto }]}>Estagiários Alocados</Text>
        <View style={[styles.badge, { backgroundColor: themeStyles.azul + '20' }]}>
          <Text style={[styles.badgeText, { color: themeStyles.azul }]}>{alunosList.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} />}
        >
          {alunosList.length === 0 ? (
            <View style={[styles.emptyBox, { borderColor: themeStyles.borda, backgroundColor: themeStyles.card }]}>
              <Ionicons name="people-circle" size={60} color={themeStyles.azul} style={{ marginBottom: 15 }} />
              <Text style={[styles.emptyTitle, { color: themeStyles.texto }]}>Nenhum estagiário!</Text>
              <Text style={[styles.emptyDesc, { color: themeStyles.textoSecundario }]}>
                A tua empresa ainda não tem alunos associados pelo professor neste momento.
              </Text>
            </View>
          ) : (
            alunosList.map((aluno, index) => {
              const status = getStatus(aluno.data_fim);
              const progressoPercent = aluno.horas_totais > 0 ? (aluno.horas_concluidas / aluno.horas_totais) * 100 : 0;
              
              return (
                <TouchableOpacity 
                  key={index} 
                  activeOpacity={0.7}
                  onPress={() => router.push({
                    pathname: '/Empresas/detalhesAluno',
                    params: { estagio_id: aluno.id_estagio, aluno_nome: aluno.aluno_nome }
                  })}
                  style={[styles.card, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda, borderLeftColor: themeStyles.azul }]}
                >
                  <View style={styles.cardHeader}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1, gap: 10 }}>
                      <View style={[styles.avatar, { backgroundColor: themeStyles.azul + '20' }]}>
                        <Ionicons name="person" size={18} color={themeStyles.azul} />
                      </View>
                      <Text style={[styles.alunoName, { color: themeStyles.texto }]} numberOfLines={1}>
                        {aluno.aluno_nome}
                      </Text>
                    </View>
                    <View style={[styles.statusTag, { backgroundColor: status.bg }]}>
                      <Text style={[styles.statusTagText, { color: status.cor }]}>{status.texto}</Text>
                    </View>
                  </View>

                  <View style={[styles.divider, { backgroundColor: themeStyles.borda }]} />

                  <View style={styles.infoRow}>
                    <View style={styles.infoCol}>
                      <Text style={[styles.infoLabel, { color: themeStyles.textoSecundario }]}>INÍCIO</Text>
                      <Text style={[styles.infoValue, { color: themeStyles.texto }]}>{formatarData(aluno.data_inicio)}</Text>
                    </View>
                    <View style={styles.infoCol}>
                      <Text style={[styles.infoLabel, { color: themeStyles.textoSecundario }]}>FIM PREVISTO</Text>
                      <Text style={[styles.infoValue, { color: themeStyles.texto }]}>{formatarData(aluno.data_fim)}</Text>
                    </View>
                  </View>

                  <View style={styles.progressSection}>
                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 }}>
                      <Text style={[styles.infoLabel, { color: themeStyles.textoSecundario }]}>HORAS REALIZADAS</Text>
                      <Text style={[styles.horasValue, { color: themeStyles.azul }]}>{aluno.horas_concluidas} / {aluno.horas_totais}h</Text>
                    </View>
                    <View style={[styles.progressBarBg, { backgroundColor: themeStyles.borda }]}>
                      <View style={[styles.progressBarFill, { backgroundColor: themeStyles.azul, width: `${Math.min(progressoPercent, 100)}%` }]} />
                    </View>
                  </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' },
  avatar: { width: 36, height: 36, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
  alunoName: { fontSize: 17, fontWeight: '900', flex: 1 },
  statusTag: { paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
  statusTagText: { fontSize: 9, fontWeight: '900', letterSpacing: 0.5 },
  divider: { height: 1, marginVertical: 15, opacity: 0.5 },
  infoRow: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 15 },
  infoCol: { flex: 1 },
  infoLabel: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', marginBottom: 4 },
  infoValue: { fontSize: 14, fontWeight: '700' },
  progressSection: { marginTop: 5 },
  horasValue: { fontSize: 12, fontWeight: '800' },
  progressBarBg: { height: 8, borderRadius: 4, width: '100%', overflow: 'hidden' },
  progressBarFill: { height: '100%', borderRadius: 4 }
});