// app/Professor/PerfilProfessor.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Animated,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTheme } from '../../themecontext';
import { supabase } from '../lib/supabase';

interface PerfilData {
  id: string;
  nome: string;
  email: string;
  n_escola: string;
  telefone: string;
  residencia: string;
  tipo: string;
  curso: string;
}

export default function PerfilProfessor() {
  const router = useRouter();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets();
  
  const [editando, setEditando] = useState(false);
  const [loading, setLoading] = useState(true);
  const [perfil, setPerfil] = useState<PerfilData | null>(null);

  const [alertConfig, setAlertConfig] = useState<{ msg: string, type: 'success' | 'error' | 'info' } | null>(null);
  const alertOpacity = useMemo(() => new Animated.Value(0), []);

  const showAlert = useCallback((msg: string, type: 'success' | 'error' | 'info' = 'info') => {
    setAlertConfig({ msg, type });
    Animated.sequence([
      Animated.timing(alertOpacity, { toValue: 1, duration: 300, useNativeDriver: true }),
      Animated.delay(3000),
      Animated.timing(alertOpacity, { toValue: 0, duration: 300, useNativeDriver: true })
    ]).start(() => setAlertConfig(null));
  }, []);

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#FFFFFF',
    card: isDarkMode ? '#161618' : '#F8FAFC',
    texto: isDarkMode ? '#F8FAFC' : '#1A365D',
    secundario: isDarkMode ? '#94A3B8' : '#718096',
    azul: '#2390a6',
    laranja: '#E38E00',
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : '#F0F9FA',
    vermelhoSuave: isDarkMode ? 'rgba(239, 68, 68, 0.15)' : '#FFF5F5',
    vermelho: '#EF4444',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    verde: '#38A169',
  }), [isDarkMode]);

  useEffect(() => { carregarPerfil(); }, []);

  async function carregarPerfil() {
    try {
      setLoading(true);
      
      // 1. Obter a sessão atual de forma limpa
      const { data: { session }, error: sessionError } = await supabase.auth.getSession();
      
      if (sessionError || !session) {
        router.replace('/');
        return;
      }

      // 2. Buscar o perfil filtrando pelo ID da sessão e garantindo que o tipo é PROFESSOR
      // Isso impede que, se a sessão mudar para aluno, os dados apareçam aqui
      const { data, error } = await supabase
        .from('profiles')
        .select('*')
        .eq('id', session.user.id)
        .eq('tipo', 'professor') // Filtro de segurança
        .single();

      if (error || !data) {
        // Se for um aluno a tentar aceder a esta página de professor, expulsamos
        showAlert('Acesso negado ou perfil não encontrado.', 'error');
        await supabase.auth.signOut();
        router.replace('/');
        return;
      }

      setPerfil(data);
    } catch (error: any) {
      console.error(error);
      showAlert('Erro ao carregar dados.', 'error');
    } finally {
      setLoading(false);
    }
  }

  const guardarPerfil = async () => {
    if (!perfil) return;
    try {
      const { error } = await supabase
        .from('profiles')
        .update({
          nome: perfil.nome,
          telefone: perfil.telefone,
          residencia: perfil.residencia,
          n_escola: perfil.n_escola,
          curso: perfil.curso
        })
        .eq('id', perfil.id);
      
      if (error) throw error;
      setEditando(false);
      showAlert('Perfil atualizado!', 'success');
    } catch (error: any) {
      showAlert('Erro ao gravar dados.', 'error');
    }
  };

  const terminarSessao = async () => {
    await supabase.auth.signOut();
    router.replace('/');
  };

  if (loading) {
    return (
      <View style={[styles.centered, { backgroundColor: cores.fundo }]}>
        <ActivityIndicator size="large" color={cores.azul} />
      </View>
    );
  }

  return (
    <View style={{ flex: 1, backgroundColor: cores.fundo }}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} translucent backgroundColor="transparent" />
      
      {alertConfig && (
        <Animated.View style={[
          styles.alertBar, 
          { 
            opacity: alertOpacity, 
            backgroundColor: alertConfig.type === 'error' ? cores.vermelho : alertConfig.type === 'success' ? cores.verde : cores.azul,
            top: insets.top + 10 
          }
        ]}>
          <Ionicons name={alertConfig.type === 'error' ? "alert-circle" : "checkmark-circle"} size={20} color="#fff" />
          <Text style={styles.alertText}>{alertConfig.msg}</Text>
        </Animated.View>
      )}

      <SafeAreaView style={styles.safe} edges={['top', 'left', 'right']}>
        
        <View style={styles.topBar}>
          <TouchableOpacity style={[styles.backBtn, { borderColor: cores.borda }]} onPress={() => router.back()}>
            <Ionicons name="arrow-back" size={22} color={cores.azul} />
          </TouchableOpacity>
          <Text style={[styles.topTitle, { color: cores.texto }]}>O Meu Perfil</Text>
          <TouchableOpacity 
            style={[styles.editBtn, { backgroundColor: editando ? cores.laranja : cores.card, borderColor: editando ? cores.laranja : cores.borda }]} 
            onPress={() => editando ? guardarPerfil() : setEditando(true)}
          >
            <Ionicons name={editando ? "checkmark-sharp" : "create-outline"} size={20} color={editando ? "#fff" : cores.azul} />
          </TouchableOpacity>
        </View>

        <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
          
          <View style={styles.profileHeader}>
            <View style={[styles.avatarBorder, { borderColor: cores.azul }]}>
              <View style={[styles.avatar, { backgroundColor: cores.azul }]}>
                <Text style={styles.avatarLetter}>{perfil?.nome?.charAt(0).toUpperCase()}</Text>
              </View>
            </View>
            <Text style={[styles.userName, { color: cores.texto }]}>{perfil?.nome}</Text>
            <View style={[styles.roleBadge, { backgroundColor: cores.azulSuave }]}>
              <Text style={[styles.userRole, { color: cores.azul }]}>PROFESSOR • {perfil?.curso}</Text>
            </View>
          </View>

          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <ModernInput label="Nome do Docente" icon="person" value={perfil?.nome || ''} editable={editando} 
              onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, nome: v } : null)} cores={cores} />

            <ModernInput label="Curso Associado" icon="school" value={perfil?.curso || ''} editable={editando}
              onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, curso: v } : null)} cores={cores} />

            <ModernInput label="Email de Login" icon="mail" value={perfil?.email || ''} editable={false} cores={cores} />

            <View style={styles.row}>
                <View style={{ flex: 1, marginRight: 10 }}>
                    <ModernInput label="Nº Mecanográfico" icon="id-card" value={perfil?.n_escola || ''} editable={editando}
                        onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, n_escola: v } : null)} cores={cores} />
                </View>
                <View style={{ flex: 1.5 }}>
                    <ModernInput label="Contacto" icon="call" value={perfil?.telefone || ''} editable={editando}
                        onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, telefone: v } : null)} keyboardType="phone-pad" cores={cores} />
                </View>
            </View>
          </View>

          <View style={styles.actionsContainer}>
            <TouchableOpacity style={[styles.menuItem, { backgroundColor: cores.card, borderColor: cores.borda }]}
              onPress={() => router.push('/Professor/redefenirsenha2')}>
              <View style={[styles.menuIcon, { backgroundColor: cores.azulSuave }]}>
                <Ionicons name="shield-checkmark" size={20} color={cores.azul} />
              </View>
              <Text style={[styles.menuText, { color: cores.texto }]}>Segurança da Conta</Text>
              <Ionicons name="chevron-forward" size={18} color={cores.secundario} />
            </TouchableOpacity>

            <TouchableOpacity style={[styles.menuItem, { backgroundColor: cores.card, borderColor: cores.borda }]}
              onPress={terminarSessao}>
              <View style={[styles.menuIcon, { backgroundColor: cores.vermelhoSuave }]}>
                <Ionicons name="power" size={20} color={cores.vermelho} />
              </View>
              <Text style={[styles.menuText, { color: cores.vermelho }]}>Sair do Sistema</Text>
            </TouchableOpacity>
          </View>

          {editando && (
             <TouchableOpacity style={styles.cancelBtn} onPress={() => { setEditando(false); carregarPerfil(); }}>
               <Text style={[styles.cancelText, { color: cores.laranja }]}>Reverter Alterações</Text>
             </TouchableOpacity>
          )}

        </ScrollView>
      </SafeAreaView>
    </View>
  );
}

const ModernInput = ({ label, icon, cores, editable, ...props }: any) => (
  <View style={styles.inputWrapper}>
    <Text style={[styles.inputLabel, { color: cores.secundario }]}>{label}</Text>
    <View style={[styles.inputContainer, { backgroundColor: editable ? cores.fundo : cores.azulSuave, borderColor: editable ? cores.laranja : 'transparent' }]}>
      <Ionicons name={icon} size={18} color={editable ? cores.laranja : cores.azul} style={{ marginRight: 12 }} />
      <TextInput {...props} editable={editable} style={[styles.textInput, { color: cores.texto }]} />
    </View>
  </View>
);

const styles = StyleSheet.create({
  safe: { flex: 1 },
  centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  alertBar: { position: 'absolute', left: 20, right: 20, padding: 15, borderRadius: 12, flexDirection: 'row', alignItems: 'center', zIndex: 9999, elevation: 5 },
  alertText: { color: '#fff', fontWeight: '700', marginLeft: 10, fontSize: 13 },
  topBar: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 24, paddingVertical: 15 },
  backBtn: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  editBtn: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1, elevation: 2 },
  topTitle: { fontSize: 18, fontWeight: '900', letterSpacing: -0.5 },
  scrollContent: { paddingHorizontal: 24, paddingBottom: 50 },
  profileHeader: { alignItems: 'center', marginVertical: 35 },
  avatarBorder: { padding: 4, borderRadius: 100, borderWidth: 2, position: 'relative' },
  avatar: { width: 90, height: 90, borderRadius: 45, alignItems: 'center', justifyContent: 'center' },
  avatarLetter: { color: '#fff', fontSize: 36, fontWeight: '900' },
  userName: { fontSize: 24, fontWeight: '900', marginTop: 15, letterSpacing: -0.5 },
  roleBadge: { paddingHorizontal: 12, paddingVertical: 4, borderRadius: 8, marginTop: 8 },
  userRole: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1 },
  card: { borderRadius: 28, padding: 24, marginBottom: 20, borderWidth: 1 },
  inputWrapper: { marginBottom: 18 },
  inputLabel: { fontSize: 10, fontWeight: '900', textTransform: 'uppercase', marginBottom: 8, marginLeft: 4, letterSpacing: 0.5 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, borderRadius: 18, borderWidth: 1.5 },
  textInput: { flex: 1, fontSize: 15, fontWeight: '700' },
  row: { flexDirection: 'row' },
  actionsContainer: { gap: 12 },
  menuItem: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 22, borderWidth: 1 },
  menuIcon: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  menuText: { flex: 1, marginLeft: 15, fontSize: 15, fontWeight: '800' },
  cancelBtn: { marginTop: 25, alignItems: 'center' },
  cancelText: { fontSize: 14, fontWeight: '800', textDecorationLine: 'underline' }
});