// app/Aluno/PerfilAluno.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';

export default function PerfilAluno() {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const insets = useSafeAreaInsets();
  
  const [loading, setLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [perfil, setPerfil] = useState<any>(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 azulPetroleo = '#2390a6';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0F0F0F' : '#F8FAFC',
    card: isDarkMode ? '#1A1A1A' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    secundario: isDarkMode ? '#94A3B8' : '#64748B',
    azul: azulPetroleo,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : 'rgba(35, 144, 166, 0.1)',
    vermelhoSuave: isDarkMode ? 'rgba(239, 68, 68, 0.15)' : 'rgba(239, 68, 68, 0.1)',
    vermelho: '#EF4444',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    verde: '#10B981',
  }), [isDarkMode]);

  const formatarParaExibir = (data: string) => {
    if (!data) return '';
    const [ano, mes, dia] = data.split('-');
    return `${dia}-${mes}-${ano}`;
  };

  const formatarParaSalvar = (data: string) => {
    if (!data || data.length < 10) return null;
    const [dia, mes, ano] = data.split('-');
    return `${ano}-${mes}-${dia}`;
  };

  const aplicarMascaraData = (text: string) => {
    const cleaned = text.replace(/\D/g, '');
    let formatted = cleaned;
    if (cleaned.length > 2) formatted = `${cleaned.slice(0, 2)}-${cleaned.slice(2)}`;
    if (cleaned.length > 4) formatted = `${cleaned.slice(0, 2)}-${cleaned.slice(2, 4)}-${cleaned.slice(4, 8)}`;
    return formatted;
  };

  const carregarDados = async () => {
    try {
      setLoading(true);
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

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

      if (error) throw error;

      if (profile?.data_nascimento) {
        profile.data_nascimento = formatarParaExibir(profile.data_nascimento);
      }

      setPerfil({ ...profile, email: user.email });
    } catch (e) {
      showAlert('Erro ao carregar perfil.', 'error');
    } finally {
      setLoading(false);
    }
  };

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

  const salvarPerfil = async () => {
    try {
      const dataBD = formatarParaSalvar(perfil.data_nascimento);
      const { error } = await supabase.from('profiles').update({
        nome: perfil.nome,
        telefone: perfil.telefone,
        residencia: perfil.residencia,
        data_nascimento: dataBD,
        curso: perfil.curso,
        n_escola: perfil.n_escola
      }).eq('id', perfil.id);

      if (error) throw error;
      setIsEditing(false);
      showAlert('Perfil guardado!', 'success');
    } catch (e) {
      showAlert('Erro ao salvar. Verifica os campos.', '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']}>
        <View style={styles.topBar}>
          <TouchableOpacity style={[styles.backBtn, { backgroundColor: cores.card }]} onPress={() => router.back()}>
            <Ionicons name="arrow-back" size={22} color={cores.texto} />
          </TouchableOpacity>
          <Text style={[styles.topTitle, { color: cores.texto }]}>O Meu Perfil</Text>
          <TouchableOpacity 
            style={[styles.editBtn, { backgroundColor: isEditing ? cores.azul : cores.card }]} 
            onPress={() => isEditing ? salvarPerfil() : setIsEditing(true)}
          >
            <Ionicons name={isEditing ? "checkmark" : "create-outline"} size={20} color={isEditing ? "#fff" : cores.azul} />
          </TouchableOpacity>
        </View>

        <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
          
          <View style={styles.profileHeader}>
            <View style={[styles.avatarContainer, { 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>
            <Text style={[styles.userRole, { color: cores.secundario }]}>{perfil?.curso || 'Sem Curso'} • {perfil?.n_escola || '---'}</Text>
          </View>

          {/* DADOS ACADÉMICOS */}
          <Text style={[styles.sectionTitle, { color: cores.secundario }]}>Informação Académica</Text>
          <View style={[styles.card, { backgroundColor: cores.card, marginBottom: 20 }]}>
            <View style={styles.row}>
                <View style={{ flex: 1, marginRight: 10 }}>
                    <ModernInput 
                        label="Nº Aluno" icon="card-outline" 
                        value={perfil?.n_escola || ''} 
                        editable={isEditing} 
                        onChangeText={(v: string) => setPerfil({...perfil, n_escola: v})} 
                        cores={cores} keyboardType="numeric"
                    />
                </View>
                <View style={{ flex: 1 }}>
                    <ModernInput 
                        label="Curso (Sigla)" icon="school-outline" 
                        value={perfil?.curso || ''} 
                        editable={isEditing} 
                        onChangeText={(v: string) => setPerfil({...perfil, curso: v})} 
                        cores={cores} autoCapitalize="characters"
                    />
                </View>
            </View>
            <ModernInput label="E-mail Institucional" icon="mail-outline" value={perfil?.email || ''} editable={false} cores={cores} />
          </View>

          {/* DADOS PESSOAIS */}
          <Text style={[styles.sectionTitle, { color: cores.secundario }]}>Dados Pessoais</Text>
          <View style={[styles.card, { backgroundColor: cores.card }]}>
            <ModernInput label="Nome Completo" icon="person-outline" value={perfil?.nome || ''} editable={isEditing} onChangeText={(v: string) => setPerfil({...perfil, nome: v})} cores={cores} />
            
            <View style={styles.row}>
                <View style={{ flex: 1, marginRight: 10 }}>
                    <ModernInput 
                        label="Nascimento" icon="calendar-outline" 
                        value={perfil?.data_nascimento || ''} 
                        editable={isEditing} 
                        onChangeText={(v: string) => setPerfil({...perfil, data_nascimento: aplicarMascaraData(v)})} 
                        cores={cores} maxLength={10} keyboardType="numeric"
                    />
                </View>
                <View style={{ flex: 1.2 }}>
                    <ModernInput label="Telefone" icon="call-outline" value={perfil?.telefone || ''} editable={isEditing} onChangeText={(v: string) => setPerfil({...perfil, telefone: v})} keyboardType="phone-pad" cores={cores} />
                </View>
            </View>

            <ModernInput label="Residência" icon="location-outline" value={perfil?.residencia || ''} editable={isEditing} onChangeText={(v: string) => setPerfil({...perfil, residencia: v})} cores={cores} />
          </View>

          {/* ACÇÕES */}
          <View style={[styles.actionsContainer, { marginTop: 30 }]}>
            <TouchableOpacity style={[styles.menuItem, { backgroundColor: cores.card }]} onPress={() => router.push('/Aluno/redefenirsenha')}>
              <View style={[styles.menuIcon, { backgroundColor: cores.azulSuave }]}>
                <Ionicons name="lock-closed-outline" size={20} color={cores.azul} />
              </View>
              <Text style={[styles.menuText, { color: cores.texto }]}>Alterar Palavra-passe</Text>
              <Ionicons name="chevron-forward" size={18} color={cores.secundario} />
            </TouchableOpacity>

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

          {isEditing && (
             <TouchableOpacity style={styles.cancelBtn} onPress={() => { setIsEditing(false); carregarDados(); }}>
               <Text style={[styles.cancelText, { color: cores.secundario }]}>Cancelar Edição</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: cores.fundo, borderColor: editable ? cores.azul : cores.borda, opacity: editable ? 1 : 0.8 }]}>
      <Ionicons name={icon} size={18} color={cores.azul} style={{ marginRight: 8 }} />
      <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' },
  alertBar: { position: 'absolute', left: 20, right: 20, padding: 15, borderRadius: 15, flexDirection: 'row', alignItems: 'center', zIndex: 9999, elevation: 10 },
  alertText: { color: '#fff', fontWeight: '700', marginLeft: 10, flex: 1 },
  topBar: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 15 },
  backBtn: { width: 42, height: 42, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  editBtn: { width: 42, height: 42, borderRadius: 12, justifyContent: 'center', alignItems: 'center', elevation: 2 },
  topTitle: { fontSize: 18, fontWeight: '800' },
  scrollContent: { paddingHorizontal: 20, paddingBottom: 40 },
  profileHeader: { alignItems: 'center', marginVertical: 15 },
  avatarContainer: { padding: 6, borderRadius: 100, borderWidth: 2, borderStyle: 'dashed' },
  avatar: { width: 80, height: 80, borderRadius: 40, alignItems: 'center', justifyContent: 'center', elevation: 4 },
  avatarLetter: { color: '#fff', fontSize: 32, fontWeight: '800' },
  userName: { fontSize: 22, fontWeight: '900', marginTop: 12 },
  userRole: { fontSize: 14, fontWeight: '600' },
  sectionTitle: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1.2, marginLeft: 10, marginBottom: 10, marginTop: 10 },
  card: { borderRadius: 24, padding: 20, elevation: 2, shadowColor: '#000', shadowOpacity: 0.05, shadowRadius: 10 },
  inputWrapper: { marginBottom: 15 },
  inputLabel: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', marginBottom: 6, marginLeft: 4 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 10, height: 50, borderRadius: 16, borderWidth: 1.5 },
  textInput: { flex: 1, fontSize: 14, fontWeight: '600' },
  row: { flexDirection: 'row' },
  actionsContainer: { gap: 10 },
  menuItem: { flexDirection: 'row', alignItems: 'center', padding: 12, borderRadius: 18, elevation: 1 },
  menuIcon: { width: 38, height: 38, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  menuText: { flex: 1, marginLeft: 12, fontSize: 14, fontWeight: '700' },
  cancelBtn: { marginTop: 20, alignItems: 'center' },
  cancelText: { fontSize: 13, fontWeight: '600', textDecorationLine: 'underline' }
});