// 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,
  Alert,
  Dimensions,
  ScrollView,
  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';

const { width } = Dimensions.get('window');

export default function EmpresaHome() {
  const router = useRouter();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets();
  
  const [empresaNome, setEmpresaNome] = useState<string>('');
  const [loading, setLoading] = useState(true);

  // Paleta EPVC (mantendo a consistência com o Prof)
  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#F4F7FA',
    card: isDarkMode ? '#161618' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    textoSecundario: isDarkMode ? '#94A3B8' : '#64748B',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : '#E0F2F4',
    laranjaSuave: isDarkMode ? 'rgba(227, 142, 0, 0.15)' : '#FEF3E6',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    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 && empresa.nome) {
        setEmpresaNome(empresa.nome);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleLogout = () => {
    Alert.alert('Terminar Sessão', 'Tens a certeza que pretendes sair?', [
      { text: 'Cancelar', style: 'cancel' },
      { text: 'Sair', style: 'destructive', onPress: () => supabase.auth.signOut().then(() => router.replace('/')) }
    ]);
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: cores.fundo }} edges={['top', 'left', 'right']}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} backgroundColor={cores.fundo} />
      
      <ScrollView 
        contentContainerStyle={[
          styles.content, 
          { paddingBottom: insets.bottom + 40 }
        ]} 
        showsVerticalScrollIndicator={false}
      >
        
        {/* Cabeçalho */}
        <View style={styles.header}>
          <View style={styles.headerRow}>
            <View style={{ flex: 1, paddingRight: 15 }}>
              <View style={[styles.badgeEpvc, { backgroundColor: cores.laranjaSuave }]}>
                <Ionicons name="business" size={12} color={cores.laranja} />
                <Text style={[styles.badgeTxt, { color: cores.laranja }]}>Painel da Entidade Parceira</Text>
              </View>
              {loading ? (
                <ActivityIndicator size="small" color={cores.azul} style={{ marginTop: 8, alignSelf: 'flex-start' }} />
              ) : (
                <Text style={[styles.name, { color: cores.texto }]} numberOfLines={1}>
                  Olá, {empresaNome || 'Empresa'}
                </Text>
              )}
              <Text style={[styles.subtitle, { color: cores.textoSecundario }]}>Gestão de Estagiários EPVC</Text>
            </View>
          </View>
        </View>

        {/* Criar Registo / Ação Imediata (Hero Card) */}
        <TouchableOpacity 
          style={[styles.heroCard, { backgroundColor: cores.laranja }]}
          activeOpacity={0.85}
          onPress={() => router.push('/Empresas/pedidos')}
        >
          <Ionicons name="document-text" size={120} color="#FFF" style={styles.heroWatermark} />
          <View style={styles.heroContent}>
            <View style={{ flex: 1, paddingRight: 10 }}>
              <Text style={styles.heroTitle}>Validações</Text>
              <Text style={styles.heroSubtitle}>Aprovar presenças e sumários dos alunos</Text>
            </View>
            <View style={styles.heroBtn}>
              <Ionicons name="arrow-forward" size={20} color={cores.laranja} />
            </View>
          </View>
        </TouchableOpacity>

        {/* SECÇÃO: Gestão de Estágios */}
        <View style={styles.sectionContainer}>
          <Text style={[styles.sectionTitle, { color: cores.textoSecundario }]}>Gestão de Estágios</Text>
          <View style={styles.grid}>
            <MenuCard icon="people" title="Alunos" subtitle="Gerir os teus estagiários" onPress={() => router.push('/Empresas/alunos')} cores={cores} corDestaque={cores.azul} />
            <MenuCard icon="star" title="Avaliações" subtitle="Avaliar desempenho" onPress={() => router.push('/Empresas/avaliacoesEmpresa')} cores={cores} corDestaque={cores.azul} />
          </View>
        </View>

        {/* SECÇÃO: Sistema */}
        <View style={styles.sectionContainer}>
          <Text style={[styles.sectionTitle, { color: cores.textoSecundario }]}>Sistema</Text>
          <View style={styles.grid}>
            <MenuCard icon="settings" title="Definições" subtitle="Ajustar dados da conta" onPress={() => router.push('/Empresas/definicoesEmpresa')} cores={cores} corDestaque={cores.textoSecundario} />
            <MenuCard icon="log-out" title="Sair" subtitle="Terminar a sessão" onPress={handleLogout} cores={cores} corDestaque={cores.vermelho} />
          </View>
        </View>

        <View style={styles.footer}>
          <Ionicons name="infinite-outline" size={24} color={cores.borda} style={{ marginBottom: 5 }} />
          <Text style={[styles.footerTxt, { color: cores.textoSecundario }]}>Estágios+ • Portal da Empresa</Text>
        </View>

      </ScrollView>
    </SafeAreaView>
  );
}

// COMPONENTE DE CARTÃO REFORMULADO
function MenuCard({ icon, title, subtitle, onPress, cores, corDestaque, fullWidth = false }: any) {
  const { isDarkMode } = useTheme();

  return (
    <TouchableOpacity 
      style={[
        styles.card, 
        { 
            backgroundColor: cores.card, 
            borderColor: cores.borda,
            width: fullWidth ? '100%' : (width - 56) / 2, // Ajustado ligeiramente o cálculo da largura
        }
      ]} 
      onPress={onPress}
      activeOpacity={0.7}
    >
      <Ionicons name={icon} size={80} color={corDestaque} style={[styles.cardWatermark, { opacity: isDarkMode ? 0.05 : 0.03 }]} />
      
      <View style={[styles.iconWrapper, { backgroundColor: corDestaque + '15' }]}>
        <Ionicons name={icon} size={22} color={corDestaque} />
      </View>
      
      <View style={styles.cardTextContainer}>
        <Text style={[styles.cardTitle, { color: cores.texto }]}>{title}</Text>
        <Text style={[styles.cardSubtitle, { color: cores.textoSecundario }]}>{subtitle}</Text>
      </View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  content: { padding: 20 },
  
  // Header
  header: { marginBottom: 25, marginTop: 10 },
  headerRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  badgeEpvc: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 10, alignSelf: 'flex-start', marginBottom: 8 },
  badgeTxt: { fontSize: 10, fontWeight: '900', letterSpacing: 1, marginLeft: 4 },
  name: { fontSize: 26, fontWeight: '900', letterSpacing: -0.5 },
  subtitle: { fontSize: 14, fontWeight: '500', marginTop: 2 },
  avatarMini: { width: 56, height: 56, borderRadius: 20, justifyContent: 'center', alignItems: 'center', borderWidth: 2 },
  avatarTxt: { fontSize: 24, fontWeight: '900' },

  // Hero Card (Ação Imediata)
  heroCard: { borderRadius: 28, padding: 24, minHeight: 140, justifyContent: 'flex-end', overflow: 'hidden', elevation: 8, shadowColor: '#E38E00', shadowOpacity: 0.3, shadowRadius: 12, shadowOffset: { width: 0, height: 6 }, marginBottom: 30 },
  heroWatermark: { position: 'absolute', right: -20, top: -20, opacity: 0.2, transform: [{ rotate: '15deg' }] },
  heroContent: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end' },
  heroTitle: { color: '#FFF', fontSize: 24, fontWeight: '900', letterSpacing: -0.5 },
  heroSubtitle: { color: 'rgba(255, 255, 255, 0.8)', fontSize: 13, fontWeight: '600', marginTop: 4 },
  heroBtn: { width: 44, height: 44, backgroundColor: '#FFF', borderRadius: 16, justifyContent: 'center', alignItems: 'center' },

  // Secções e Grid
  sectionContainer: { marginBottom: 25 },
  sectionTitle: { fontSize: 12, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1.5, marginBottom: 12, marginLeft: 4 },
  grid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between' },
  
  // Cartões Menores
  card: {
    borderRadius: 24,
    padding: 18,
    marginBottom: 16,
    borderWidth: 1,
    overflow: 'hidden',
    elevation: 2,
    shadowColor: '#000',
    shadowOpacity: 0.04,
    shadowRadius: 10,
    shadowOffset: { width: 0, height: 4 }
  },
  cardWatermark: { position: 'absolute', right: -15, bottom: -15, transform: [{ rotate: '-10deg' }] },
  iconWrapper: { width: 42, height: 42, borderRadius: 14, justifyContent: 'center', alignItems: 'center', marginBottom: 16 },
  cardTextContainer: { marginTop: 'auto' },
  cardTitle: { fontSize: 16, fontWeight: '800', letterSpacing: -0.3 },
  cardSubtitle: { fontSize: 12, marginTop: 2, fontWeight: '600' },

  // Footer
  footer: { marginTop: 20, alignItems: 'center', paddingBottom: 20 },
  footerTxt: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1.2 }
});