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

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));
  }, [alertOpacity]);

  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#F4F7FA',
    card: isDarkMode ? '#161618' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    secundario: 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',
    vermelhoSuave: isDarkMode ? 'rgba(239, 68, 68, 0.15)' : '#FEE2E2',
    vermelho: '#EF4444',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    verde: '#10B981',
    inputFundo: isDarkMode ? '#252525' : '#F8FAFC',
  }), [isDarkMode]);

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

  async function carregarPerfil() {
    try {
      setLoading(true);
      
      const { data: { session }, error: sessionError } = await supabase.auth.getSession();
      
      if (sessionError || !session) {
        router.replace('/');
        return;
      }

      const { data, error } = await supabase
        .from('profiles')
        .select('*')
        .eq('id', session.user.id)
        .eq('tipo', 'professor') 
        .single();

      if (error || !data) {
        showAlert('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;

    // 🟢 VALIDAÇÃO: Se algum campo estiver vazio ou for apenas espaços, dispara erro
    if (
      !perfil.nome?.trim() ||
      !perfil.telefone?.trim() ||
      !perfil.residencia?.trim() ||
      !perfil.n_escola?.trim() ||
      !perfil.curso?.trim()
    ) {
      showAlert('Todos os campos são de preenchimento obrigatório.', 'error');
      return; // Corta a função aqui para não gravar na base de dados
    }

    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 com sucesso!', '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.toastContainer, 
          { 
            opacity: alertOpacity, 
            backgroundColor: alertConfig.type === 'error' ? cores.vermelho : alertConfig.type === 'success' ? cores.verde : cores.azul,
            top: insets.top + 10 
          }
        ]}>
          <Ionicons name={alertConfig.type === 'error' ? "warning" : "checkmark-circle"} size={22} color="#fff" />
          <Text style={styles.toastText}>{alertConfig.msg}</Text>
        </Animated.View>
      ) : null}

      <SafeAreaView style={styles.safe} edges={['top', 'left', 'right']}>
        
        {/* HEADER */}
        <View style={styles.header}>
          <TouchableOpacity style={[styles.btnAction, { borderColor: cores.borda, backgroundColor: cores.card }]} onPress={() => router.back()}>
            <Ionicons name="chevron-back" size={24} color={cores.azul} />
          </TouchableOpacity>
          <View style={{ alignItems: 'center' }}>
            <Text style={[styles.headerTitle, { color: cores.texto }]}>O Meu Perfil</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>Estágios+</Text>
          </View>
          <TouchableOpacity 
            style={[
              styles.btnAction, 
              { 
                backgroundColor: editando ? cores.laranja : cores.card, 
                borderColor: editando ? cores.laranja : cores.borda 
              }
            ]} 
            onPress={() => editando ? guardarPerfil() : setEditando(true)}
          >
            <Ionicons name={editando ? "save" : "pencil"} size={20} color={editando ? "#fff" : cores.azul} />
          </TouchableOpacity>
        </View>

        <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
          
          {/* HEADER DO PERFIL (AVATAR) */}
          <View style={styles.profileHeader}>
            <View style={[styles.avatarBorder, { borderColor: cores.azulSuave }]}>
              <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.laranjaSuave }]}>
              <Ionicons name="school" size={12} color={cores.laranja} style={{ marginRight: 6 }} />
              <Text style={[styles.userRole, { color: cores.laranja }]}>Professor • {perfil?.curso || 'EPVC'}</Text>
            </View>
          </View>

          <View style={styles.cardsContainer}>
            
            {/* CARTÃO: DADOS PESSOAIS */}
            <View style={[styles.sectionCard, { backgroundColor: cores.card, borderColor: cores.borda }]}>
              <SectionHeader icon="person" title="Dados Pessoais" cores={cores} />
              
              <ModernInput label="Nome" icon="text" value={perfil?.nome || ''} editable={editando} 
                onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, nome: v } : null)} cores={cores} />
              
              <ModernInput label="Email" icon="mail" value={perfil?.email || ''} editable={false} cores={cores} />
              
              <View style={{ flexDirection: 'row', gap: 12 }}>
                <View style={{ flex: 1 }}>
                  <ModernInput label="Contacto" icon="call" value={perfil?.telefone || ''} editable={editando} keyboardType="phone-pad"
                    onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, telefone: v } : null)} cores={cores} />
                </View>
              </View>

              <ModernInput label="Morada" icon="home" value={perfil?.residencia || ''} editable={editando} 
                onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, residencia: v } : null)} cores={cores} />
            </View>

            {/* CARTÃO: DADOS PROFISSIONAIS */}
            <View style={[styles.sectionCard, { backgroundColor: cores.card, borderColor: cores.borda }]}>
              <SectionHeader icon="library" title="Dados Profissionais" cores={cores} />
              
              <View style={{ flexDirection: 'row', gap: 12 }}>
                <View style={{ flex: 1 }}>
                  <ModernInput label="Nº de Professor" icon="id-card" value={perfil?.n_escola || ''} editable={editando} keyboardType="numeric"
                    onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, n_escola: v } : null)} cores={cores} />
                </View>
                <View style={{ flex: 1.5 }}>
                  <ModernInput label="Curso" icon="briefcase" value={perfil?.curso || ''} editable={editando}
                    onChangeText={(v: string) => setPerfil(prev => prev ? { ...prev, curso: v } : null)} cores={cores} />
                </View>
              </View>
            </View>

            {/* BOTÕES DE AÇÃO (SEGURANÇA E SAIR) */}
            <View style={styles.actionsContainer}>
              <TouchableOpacity 
                style={[styles.menuItem, { backgroundColor: cores.card, borderColor: cores.borda }]}
                onPress={() => router.push('/Professor/redefenirsenha2')}
                activeOpacity={0.7}
              >
                <View style={[styles.menuIcon, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="lock-closed" size={20} color={cores.azul} />
                </View>
                <Text style={[styles.menuText, { color: cores.texto }]}>Alterar palavra-passe</Text>
                <Ionicons name="chevron-forward" size={20} color={cores.secundario} />
              </TouchableOpacity>

              <TouchableOpacity 
                style={[styles.menuItem, { backgroundColor: cores.card, borderColor: cores.borda }]}
                onPress={terminarSessao}
                activeOpacity={0.7}
              >
                <View style={[styles.menuIcon, { backgroundColor: cores.vermelhoSuave }]}>
                  <Ionicons name="log-out" size={22} color={cores.vermelho} />
                </View>
                <Text style={[styles.menuText, { color: cores.vermelho }]}>Terminar sessão</Text>
              </TouchableOpacity>
            </View>

            {/* BOTÃO DE CANCELAR EDIÇÃO */}
            {editando ? (
              <TouchableOpacity style={styles.cancelBtn} onPress={() => { setEditando(false); carregarPerfil(); }}>
                <Text style={[styles.cancelText, { color: cores.secundario }]}>Cancelar e Reverter Alterações</Text>
              </TouchableOpacity>
            ) : null}

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

// COMPONENTE HEADER DE SECÇÃO
const SectionHeader = ({ icon, title, cores }: any) => (
  <View style={styles.sectionHeader}>
    <View style={[styles.iconCircle, { backgroundColor: cores.azulSuave }]}>
      <Ionicons name={icon} size={16} color={cores.azul} />
    </View>
    <Text style={[styles.sectionTitleTxt, { color: cores.texto }]}>{title}</Text>
  </View>
);

// COMPONENTE DE INPUT MODERNO
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.inputFundo : cores.fundo, 
        borderColor: editable ? cores.azul : cores.borda,
        borderWidth: editable ? 1.5 : 1,
        opacity: editable ? 1 : 0.7
      }
    ]}>
      <Ionicons name={icon} size={18} color={editable ? cores.azul : cores.secundario} style={{ marginRight: 12 }} />
      <TextInput 
        {...props} 
        editable={editable} 
        style={[styles.textInput, { color: cores.texto }]} 
        placeholderTextColor={cores.secundario}
      />
    </View>
  </View>
);

const styles = StyleSheet.create({
  safe: { flex: 1 },
  centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  
  // TOAST
  toastContainer: { position: 'absolute', left: 20, right: 20, padding: 16, borderRadius: 16, flexDirection: 'row', alignItems: 'center', zIndex: 9999, elevation: 6, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.2, shadowRadius: 8 },
  toastText: { color: '#fff', fontWeight: '800', marginLeft: 12, fontSize: 14, flex: 1 },
  
  // HEADER SUPERIOR
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 15 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  headerTitle: { fontSize: 20, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1, marginTop: 2 },
  
  scrollContent: { paddingHorizontal: 20, paddingBottom: 50 },
  
  // PERFIL HIGHLIGHT
  profileHeader: { alignItems: 'center', marginVertical: 25 },
  avatarBorder: { padding: 6, borderRadius: 100, borderWidth: 2 },
  avatar: { width: 90, height: 90, borderRadius: 45, alignItems: 'center', justifyContent: 'center', elevation: 4, shadowColor: '#2390a6', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.3, shadowRadius: 8 },
  avatarLetter: { color: '#fff', fontSize: 36, fontWeight: '900' },
  userName: { fontSize: 24, fontWeight: '900', marginTop: 15, letterSpacing: -0.5 },
  roleBadge: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 12, paddingVertical: 6, borderRadius: 10, marginTop: 8 },
  userRole: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1 },
  
  cardsContainer: { gap: 20 },

  // CARTÕES DE SECÇÃO
  sectionCard: { borderRadius: 24, padding: 20, borderWidth: 1, elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.03, shadowRadius: 8 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 20 },
  iconCircle: { width: 32, height: 32, borderRadius: 10, justifyContent: 'center', alignItems: 'center', marginRight: 10 },
  sectionTitleTxt: { fontSize: 16, fontWeight: '900', letterSpacing: -0.2 },
  
  // INPUTS
  inputWrapper: { marginBottom: 16 },
  inputLabel: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', marginBottom: 8, marginLeft: 4, letterSpacing: 0.5 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 52, borderRadius: 16 },
  textInput: { flex: 1, fontSize: 15, fontWeight: '700' },
  
  // ACÇÕES E MENU
  actionsContainer: { gap: 12, marginTop: 10 },
  menuItem: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 22, borderWidth: 1, elevation: 1, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.02, shadowRadius: 5 },
  menuIcon: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  menuText: { flex: 1, marginLeft: 15, fontSize: 15, fontWeight: '800' },
  
  cancelBtn: { marginTop: 20, alignItems: 'center', paddingVertical: 10 },
  cancelText: { fontSize: 14, fontWeight: '800', textDecorationLine: 'underline' }
});