// app/Professor/ProfessorHome.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  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 ProfessorHome() {
  const router = useRouter();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets();
  const [nome, setNome] = useState<string>('');
  const [loading, setLoading] = useState(true);

  // Paleta EPVC
  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',
  }), [isDarkMode]);

  useEffect(() => {
    async function obterNome() {
      try {
        const { data: { user } } = await supabase.auth.getUser();
        if (user) {
          const { data, error } = await supabase
            .from('profiles')
            .select('nome')
            .eq('id', user.id)
            .single();
          if (error) throw error;
          if (data?.nome) setNome(data.nome);
        }
      } catch (err: any) {
        console.error(err.message);
      } finally {
        setLoading(false);
      }
    }
    obterNome();
  }, []);

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: cores.fundo }} edges={['top', 'left', 'right']}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      
      <ScrollView 
        contentContainerStyle={[
          styles.content, 
          { paddingBottom: insets.bottom + 40 }
        ]} 
        showsVerticalScrollIndicator={false}
      >
        
        {/* Cabeçalho */}
        <View style={styles.header}>
          <View style={styles.headerRow}>
            <View style={{ flex: 1 }}>
              <View style={styles.badgeEpvc}>
                <Ionicons name="school" size={12} color={cores.azul} />
                <Text style={[styles.badgeTxt, { color: cores.azul }]}>Escola Profissional de Vila do Conde</Text>
              </View>
              {loading ? (
                <ActivityIndicator size="small" color={cores.laranja} style={{ marginTop: 8, alignSelf: 'flex-start' }} />
              ) : (
                <Text style={[styles.name, { color: cores.texto }]} numberOfLines={1}>
                  Olá, {nome ? nome.split(' ')[0] : 'Professor'}
                </Text>
              )}
              <Text style={[styles.subtitle, { color: cores.textoSecundario }]}>Controlo de Estágios Escolares</Text>
            </View>
            
            <TouchableOpacity 
              onPress={() => router.push('/Professor/PerfilProf')}
              style={[styles.avatarMini, { backgroundColor: cores.azulSuave, borderColor: cores.azul }]}
            >
              <Text style={[styles.avatarTxt, { color: cores.azul }]}>{nome?.charAt(0).toUpperCase() || 'P'}</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Criar Registo */}
        <TouchableOpacity 
          style={[styles.heroCard, { backgroundColor: cores.azul }]}
          activeOpacity={0.85}
          onPress={() => router.push('/Professor/Alunos/CriarRegisto')}
        >
          <Ionicons name="add-circle" size={120} color="#FFF" style={styles.heroWatermark} />
          <View style={styles.heroContent}>
            <View>
              <Text style={styles.heroTitle}>Novo Registo</Text>
              <Text style={styles.heroSubtitle}>Adicionar Empresa, Aluno ou Professor</Text>
            </View>
            <View style={styles.heroBtn}>
              <Ionicons name="arrow-forward" size={20} color={cores.azul} />
            </View>
          </View>
        </TouchableOpacity>

        {/* SECÇÃO: Controlo Diário */}
        <View style={styles.sectionContainer}>
          <Text style={[styles.sectionTitle, { color: cores.textoSecundario }]}>Controlo diário dos alunos</Text>
          <View style={styles.grid}>
            <MenuCard icon="calendar" title="Presenças" subtitle="Verifica a presença e a localização dos alunos" onPress={() => router.push('/Professor/Alunos/Presencas')} cores={cores} corDestaque={cores.azul} />
            <MenuCard icon="document-text" title="Sumários" subtitle="Verifica os sumários dos alunos" onPress={() => router.push('/Professor/Alunos/Sumarios')} cores={cores} corDestaque={cores.laranja} />
            <MenuCard icon="alert-circle" title="Faltas" subtitle="Verifica as faltas e as justificações" onPress={() => router.push('/Professor/Alunos/Faltas')} cores={cores} corDestaque="#EF4444" />
            <MenuCard icon="alert-circle" title="Relatórios" subtitle="Verifica e obtém relatórios" onPress={() => router.push('/Professor/Alunos/relatorios')} cores={cores} corDestaque={cores.azul} />

          </View>
        </View>

        {/* SECÇÃO: Empresas */}
        <View style={styles.sectionContainer}>
          <Text style={[styles.sectionTitle, { color: cores.textoSecundario }]}>Entidades</Text>
          <View style={styles.grid}>
            <MenuCard icon="people" title="Alunos" subtitle="Verifica e altera informações de todos os alunos" onPress={() => router.push('/Professor/Alunos/ListaAlunos')} cores={cores} corDestaque={cores.azul} fullWidth />
            <MenuCard icon="briefcase" title="Estágios" subtitle="Cria novos estágios e edita" onPress={() => router.push('/Professor/Alunos/Estagios')} cores={cores} corDestaque={cores.laranja} />
            <MenuCard icon="business" title="Empresas" subtitle="Verifica as empresas e altera dados" onPress={() => router.push('/Professor/Empresas/ListaEmpresas')} 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="Tema & Contactos" onPress={() => router.push('/Professor/defenicoes2')} cores={cores} corDestaque={cores.textoSecundario} />
            <MenuCard icon="person" title="Perfil" subtitle="Verifica e altera os teus dados" onPress={() => router.push('/Professor/PerfilProf')} cores={cores} corDestaque={cores.textoSecundario} />
          </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+ • Versão 26.5.4</Text>
        </View>

      </ScrollView>
    </SafeAreaView>
  );
}

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

  return (
    <TouchableOpacity 
      style={[
        styles.card, 
        { 
            backgroundColor: cores.card, 
            borderColor: cores.borda,
            width: fullWidth ? '100%' : (width - 60) / 2, // Se for fullWidth ocupa tudo, senão divide
        }
      ]} 
      onPress={onPress}
      activeOpacity={0.7}
    >
      {/* Marca de água no fundo para design premium */}
      <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', backgroundColor: '#E0F2F4', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 10, alignSelf: 'flex-start', marginBottom: 8 },
  badgeTxt: { fontSize: 10, fontWeight: '900', letterSpacing: 1, marginLeft: 4 },
  name: { fontSize: 28, 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 (Novo Registo)
  heroCard: { borderRadius: 28, padding: 24, minHeight: 140, justifyContent: 'flex-end', overflow: 'hidden', elevation: 8, shadowColor: '#2390a6', 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 }
});