// app/Professor/ProfessorMenu.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 { useTheme } from '../../themecontext';
import { supabase } from '../lib/supabase';

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

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

  // Paleta EPVC Extraída da Imagem
  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#FFFFFF', // Fundo branco limpo como o login
    card: isDarkMode ? '#161618' : '#F8FAFC',
    texto: isDarkMode ? '#F8FAFC' : '#1A365D', // Azul escuro para contraste
    textoSecundario: isDarkMode ? '#94A3B8' : '#718096',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : '#F0F9FA',
    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 + 20 }
        ]} 
        showsVerticalScrollIndicator={false}
      >
        
        {/* HEADER EPVC STYLE */}
        <View style={styles.header}>
          <View style={styles.headerRow}>
            <View>
              <Text style={[styles.welcome, { color: cores.laranja }]}>Olá, Professor</Text>
              {loading ? (
                <ActivityIndicator size="small" color={cores.azul} style={{ marginTop: 8, alignSelf: 'flex-start' }} />
              ) : (
                <Text style={[styles.name, { color: cores.texto }]}>{nome || 'Docente'}</Text>
              )}
            </View>
            <TouchableOpacity 
              onPress={() => router.push('/Professor/PerfilProf')}
              style={[styles.avatarMini, { backgroundColor: cores.azul }]}
            >
              <Text style={styles.avatarTxt}>{nome?.charAt(0).toUpperCase() || 'P'}</Text>
            </TouchableOpacity>
          </View>
          
          <View style={[styles.infoBanner, { backgroundColor: cores.azulSuave, borderColor: cores.azul }]}>
            <Ionicons name="school-outline" size={18} color={cores.azul} />
            <Text style={[styles.bannerTxt, { color: cores.azul }]}>Escola Profissional de Vila do Conde</Text>
          </View>
        </View>

        {/* GRID DE MENU */}
        <View style={styles.grid}>
          <MenuCard icon="document-text-outline" title="Sumários" subtitle="Registos" onPress={() => router.push('/Professor/Alunos/Sumarios')} cores={cores} />
          <MenuCard icon="calendar-outline" title="Presenças" subtitle="Controlo" onPress={() => router.push('/Professor/Alunos/Presencas')} cores={cores} />
          <MenuCard icon="alert-circle-outline" title="Faltas" subtitle="Gestão" onPress={() => router.push('/Professor/Alunos/Faltas')} cores={cores} />
          <MenuCard icon="people-outline" title="Alunos" subtitle="Turmas" onPress={() => router.push('/Professor/Alunos/ListaAlunos')} cores={cores} />
          <MenuCard icon="briefcase-outline" title="Estágios" subtitle="Projetos" onPress={() => router.push('/Professor/Alunos/Estagios')} cores={cores} />
          <MenuCard icon="business-outline" title="Empresas" subtitle="Parcerias" onPress={() => router.push('/Professor/Empresas/ListaEmpresas')} cores={cores} />
          <MenuCard icon="settings-outline" title="Definições" subtitle="Sistema" onPress={() => router.push('/Professor/defenicoes2')} cores={cores} />
          <MenuCard icon="person-outline" title="Perfil" subtitle="A minha conta" onPress={() => router.push('/Professor/PerfilProf')} cores={cores} />
        </View>

        <View style={styles.footer}>
          <View style={[styles.footerLine, { backgroundColor: cores.laranja }]} />
          <Text style={[styles.footerTxt, { color: cores.textoSecundario }]}>Estágios+ • EPVC 2026</Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

function MenuCard({ icon, title, subtitle, onPress, cores }: any) {
  return (
    <TouchableOpacity 
      style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]} 
      onPress={onPress}
      activeOpacity={0.8}
    >
      <View style={[styles.iconBox, { backgroundColor: cores.azulSuave }]}>
        <Ionicons name={icon} size={24} color={cores.azul} />
      </View>
      <View>
        <Text style={[styles.cardTitle, { color: cores.texto }]}>{title}</Text>
        <Text style={[styles.cardSubtitle, { color: cores.textoSecundario }]}>{subtitle}</Text>
      </View>
      <View style={[styles.arrowCircle, { backgroundColor: cores.laranja }]}>
        <Ionicons name="chevron-forward" size={12} color="#FFF" />
      </View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  content: { padding: 24 },
  header: { marginBottom: 35 },
  headerRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 },
  welcome: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1.5 },
  name: { fontSize: 26, fontWeight: '900', letterSpacing: -0.8, marginTop: 2 },
  avatarMini: { width: 52, height: 52, borderRadius: 18, justifyContent: 'center', alignItems: 'center', elevation: 4, shadowColor: '#000', shadowOpacity: 0.15, shadowRadius: 8 },
  avatarTxt: { color: '#fff', fontSize: 22, fontWeight: '900' },
  infoBanner: { flexDirection: 'row', alignItems: 'center', padding: 14, borderRadius: 16, borderWidth: 1, borderStyle: 'dashed' },
  bannerTxt: { fontSize: 13, fontWeight: '700', marginLeft: 10 },
  grid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between' },
  card: {
    width: (width - 64) / 2,
    borderRadius: 24,
    padding: 20,
    marginBottom: 16,
    borderWidth: 1,
    shadowColor: '#000',
    shadowOpacity: 0.03,
    shadowRadius: 15,
    elevation: 3,
  },
  iconBox: { width: 48, height: 48, borderRadius: 15, justifyContent: 'center', alignItems: 'center', marginBottom: 16 },
  cardTitle: { fontSize: 16, fontWeight: '800', letterSpacing: -0.2 },
  cardSubtitle: { fontSize: 12, marginTop: 2, fontWeight: '600', opacity: 0.7 },
  arrowCircle: { position: 'absolute', top: 20, right: 15, width: 22, height: 22, borderRadius: 11, justifyContent: 'center', alignItems: 'center' },
  footer: { marginTop: 30, alignItems: 'center' },
  footerLine: { width: 40, height: 4, borderRadius: 2, marginBottom: 15 },
  footerTxt: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1.2 }
});