// app/Empresas/EmpresaHome.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,
  Platform,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';
import { supabase } from '../../lib/supabase';
import { useTheme } from '../../themecontext';

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

  const [loading, setLoading] = useState(true);
  const [empresaNome, setEmpresaNome] = useState('');

  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',
    vermelho: '#EF4444',
  }), [isDarkMode]);

  const fetchEmpresaInfo = async () => {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

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

      if (empresa) {
        setEmpresaNome(empresa.nome);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: themeStyles.fundo }]}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      
      {/* CABEÇALHO */}
      <View style={styles.topBar}>
        <View>
          <Text style={[styles.greeting, { color: themeStyles.textoSecundario }]}>Painel da Entidade</Text>
          {loading ? (
             <ActivityIndicator size="small" color={themeStyles.azul} style={{ marginTop: 5, alignSelf: 'flex-start' }} />
          ) : (
             <Text style={[styles.title, { color: themeStyles.texto }]}>{empresaNome || 'A carregar...'}</Text>
          )}
        </View>
        <TouchableOpacity style={[styles.logoutBtn, { borderColor: themeStyles.borda }]} onPress={() => supabase.auth.signOut().then(() => router.replace('/'))}>
          <Ionicons name="log-out-outline" size={24} color={themeStyles.vermelho} />
        </TouchableOpacity>
      </View>

      <ScrollView 
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* CARTÃO DE DESTAQUE - PEDIDOS PENDENTES */}
        <Text style={[styles.sectionLabel, { color: themeStyles.textoSecundario }]}>AÇÃO IMEDIATA</Text>
        
        <TouchableOpacity 
          activeOpacity={0.8}
          style={[styles.heroCard, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda, borderLeftColor: themeStyles.laranja }]}
          onPress={() => router.push('/Empresas/pedidos')}
        >
          <View style={styles.heroContent}>
            <View style={[styles.iconWrapperLarge, { backgroundColor: themeStyles.laranja + '15' }]}>
              <Ionicons name="document-text" size={34} color={themeStyles.laranja} />
            </View>
            <View style={styles.heroTextContainer}>
              <Text style={[styles.heroTitle, { color: themeStyles.texto }]}>Validações Pendentes</Text>
              <Text style={[styles.heroDesc, { color: themeStyles.textoSecundario }]}>Aprovar presenças e sumários</Text>
            </View>
          </View>
          <Ionicons name="chevron-forward" size={24} color={themeStyles.textoSecundario} />
        </TouchableOpacity>

        {/* SECÇÃO GESTÃO - GRELHA 2 COLUNAS */}
        <Text style={[styles.sectionLabel, { color: themeStyles.textoSecundario, marginTop: 15 }]}>GESTÃO DE ESTÁGIOS</Text>
        
        <View style={styles.gridContainer}>
          <TouchableOpacity 
            activeOpacity={0.7} 
            style={[styles.gridCard, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda }]} 
            onPress={() => router.push('/Empresas/alunos')}
          >
            <View style={[styles.iconWrapper, { backgroundColor: themeStyles.azul + '15' }]}>
              <Ionicons name="people" size={26} color={themeStyles.azul} />
            </View>
            <Text style={[styles.gridCardTitle, { color: themeStyles.texto }]}>Alunos</Text>
            <Text style={[styles.gridCardDesc, { color: themeStyles.textoSecundario }]}>Gerir estagiários</Text>
          </TouchableOpacity>

          <TouchableOpacity 
            activeOpacity={0.7} 
            style={[styles.gridCard, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda }]} 
            onPress={() => router.push('/Empresas/avaliacoesEmpresa')}
          >
            <View style={[styles.iconWrapper, { backgroundColor: themeStyles.verde + '15' }]}>
              <Ionicons name="star" size={26} color={themeStyles.verde} />
            </View>
            <Text style={[styles.gridCardTitle, { color: themeStyles.texto }]}>Avaliações</Text>
            <Text style={[styles.gridCardDesc, { color: themeStyles.textoSecundario }]}>Avaliar estágios</Text>
          </TouchableOpacity>
        </View>

        {/* DEFINIÇÕES - CARTÃO LARGO INFERIOR */}
        <TouchableOpacity 
          activeOpacity={0.7}
          style={[styles.rowCard, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda }]}
          onPress={() => router.push('/Empresas/definicoesEmpresa')}
        >
          <View style={[styles.iconWrapperSmall, { backgroundColor: themeStyles.textoSecundario + '15' }]}>
            <Ionicons name="settings" size={22} color={themeStyles.textoSecundario} />
          </View>
          <View style={styles.rowTextContainer}>
            <Text style={[styles.rowTitle, { color: themeStyles.texto }]}>Definições da Conta</Text>
            <Text style={[styles.rowDesc, { color: themeStyles.textoSecundario }]}>Ajustar dados da empresa e segurança</Text>
          </View>
          <Ionicons name="chevron-forward" size={20} color={themeStyles.textoSecundario} />
        </TouchableOpacity>

      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0 },
  topBar: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 20, paddingTop: 20, paddingBottom: 15 },
  greeting: { fontSize: 13, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1 },
  title: { fontSize: 24, fontWeight: '900', marginTop: 2 },
  logoutBtn: { width: 45, height: 45, borderRadius: 14, borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  
  scrollContent: { paddingHorizontal: 20, paddingBottom: 40 },
  sectionLabel: { fontSize: 11, fontWeight: '800', letterSpacing: 1.2, marginBottom: 12, marginLeft: 5 },

  heroCard: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 20, borderRadius: 24, borderWidth: 1, borderLeftWidth: 6, marginBottom: 25, elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.05, shadowRadius: 10 },
  heroContent: { flexDirection: 'row', alignItems: 'center', flex: 1 },
  iconWrapperLarge: { width: 65, height: 65, borderRadius: 20, justifyContent: 'center', alignItems: 'center', marginRight: 15 },
  heroTextContainer: { flex: 1, paddingRight: 10 },
  heroTitle: { fontSize: 19, fontWeight: '900', marginBottom: 4 },
  heroDesc: { fontSize: 13, fontWeight: '600' },

  gridContainer: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 20 },
  gridCard: { width: '48%', padding: 20, borderRadius: 24, borderWidth: 1, alignItems: 'flex-start', elevation: 1, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.03, shadowRadius: 5 },
  iconWrapper: { padding: 12, borderRadius: 16, marginBottom: 16 },
  gridCardTitle: { fontSize: 16, fontWeight: '900', marginBottom: 4 },
  gridCardDesc: { fontSize: 12, fontWeight: '600' },

  rowCard: { flexDirection: 'row', alignItems: 'center', padding: 18, borderRadius: 20, borderWidth: 1, marginTop: 5 },
  iconWrapperSmall: { width: 45, height: 45, borderRadius: 14, justifyContent: 'center', alignItems: 'center', marginRight: 15 },
  rowTextContainer: { flex: 1 },
  rowTitle: { fontSize: 15, fontWeight: '800', marginBottom: 2 },
  rowDesc: { fontSize: 12, fontWeight: '600' }
});