import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect } from '@react-navigation/native';
import { useRouter } from 'expo-router';
import { useCallback, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Animated,
  KeyboardAvoidingView,
  Platform,
  RefreshControl,
  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';

export default function PerfilAluno() {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const insets = useSafeAreaInsets();
  
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [perfil, setPerfil] = useState<any>(null);
  const [saving, setSaving] = useState(false);

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

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0F0F0F' : '#F8FAFC',
    card: isDarkMode ? '#1A1A1A' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    secundario: isDarkMode ? '#94A3B8' : '#64748B',
    azul: '#2390a6',
    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 showAlert = useCallback((msg: string, type: 'success' | 'error') => {
    setAlertConfig({ msg, type });
    Animated.sequence([
      Animated.timing(alertOpacity, { toValue: 1, duration: 400, useNativeDriver: true }),
      Animated.delay(2500),
      Animated.timing(alertOpacity, { toValue: 0, duration: 400, useNativeDriver: true })
    ]).start(() => setAlertConfig(null));
  }, [alertOpacity]);

  const formatarDataParaUI = (dataDB: string) => {
    if (!dataDB) return '';
    const parts = dataDB.split('-');
    if (parts.length !== 3) return dataDB;
    return `${parts[2]}-${parts[1]}-${parts[0]}`; 
  };

  const formatarDataParaDB = (dataUI: string) => {
    if (!dataUI || dataUI.length !== 10) return null;
    const parts = dataUI.split('-');
    if (parts.length !== 3) return null;
    return `${parts[2]}-${parts[1]}-${parts[0]}`; 
  };

  const calcularIdade = (dataPT: string) => {
    if (!dataPT || dataPT.length !== 10) return null;
    const parts = dataPT.split('-');
    const dia = parseInt(parts[0], 10);
    const mes = parseInt(parts[1], 10);
    const ano = parseInt(parts[2], 10);

    if (ano < 1950 || ano > new Date().getFullYear()) return null;

    const hoje = new Date();
    const nascimento = new Date(ano, mes - 1, dia);
    
    if (nascimento.getDate() !== dia) return null;

    let idade = hoje.getFullYear() - nascimento.getFullYear();
    const m = hoje.getMonth() - nascimento.getMonth();
    if (m < 0 || (m === 0 && hoje.getDate() < nascimento.getDate())) {
      idade--;
    }
    return idade >= 0 ? idade : 0;
  };

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

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

      // 🟢 CORREÇÃO: Vamos buscar as DUAS tabelas sempre usando o ID do utilizador (infalível)
      const { data: pData } = await supabase.from('profiles').select('*').eq('id', user.id).single();
      const { data: aData } = await supabase.from('alunos').select('*').eq('id', user.id).maybeSingle();

      const dataFormatadaUI = formatarDataParaUI(pData?.data_nascimento);
      const idadeCalculada = dataFormatadaUI ? calcularIdade(dataFormatadaUI) : pData?.idade;

      setPerfil({ 
        ...pData, 
        ...aData, // A tabela de alunos (onde está o curso) sobrepõe e preenche o que falta
        email: user.email, 
        data_nascimento: dataFormatadaUI, 
        idade: idadeCalculada ?? 'N/A' 
      });

      Animated.timing(fadeAnim, { toValue: 1, duration: 600, useNativeDriver: true }).start();
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(
    useCallback(() => {
      buscarDados();
    }, [])
  );

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    buscarDados(true);
  }, []);

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

      const dataProntaParaDB = formatarDataParaDB(perfil.data_nascimento);

      // 1. Atualizar a tabela de Perfis Pessoais
      const { error: errorProfile } = await supabase.from('profiles').update({
        nome: perfil.nome,
        residencia: perfil.residencia,
        data_nascimento: dataProntaParaDB, 
        idade: perfil.idade !== 'N/A' ? Number(perfil.idade) : null, 
        telefone: perfil.telefone 
      }).eq('id', user.id);

      if (errorProfile) throw errorProfile;

      // 2. Atualizar a tabela de Alunos (só o nome, para manter tudo sincronizado)
      // Não lançamos erro aqui para não bloquear o utilizador se ele não tiver permissões RLS no momento
      await supabase.from('alunos').update({ nome: perfil.nome }).eq('id', user.id);

      setIsEditing(false);
      showAlert("Perfil guardado com sucesso!", "success");
      
      // OBRIGA O ECRÃ A ATUALIZAR OS DADOS VISUAIS FRESQUINHOS
      await buscarDados(); 

    } catch (e: any) {
      showAlert(e.message || "Erro ao guardar alterações.", "error");
    } finally {
      setSaving(false);
    }
  };

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

  return (
    <KeyboardAvoidingView style={{ flex: 1, backgroundColor: cores.fundo }} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      
      {alertConfig && (
        <Animated.View style={[
          styles.modernAlert, 
          { 
            opacity: alertOpacity, 
            backgroundColor: alertConfig.type === 'success' ? cores.verde : cores.vermelho, 
            top: insets.top > 0 ? insets.top + 10 : 40 
          }
        ]}>
          <Ionicons name={alertConfig.type === 'success' ? "checkmark-circle" : "alert-circle"} size={22} color="#fff" />
          <Text style={styles.modernAlertText}>{alertConfig.msg}</Text>
        </Animated.View>
      )}

      <SafeAreaView style={{ flex: 1 }} edges={['top']}>
        
        <View style={styles.headerContainer}>
          <TouchableOpacity style={[styles.roundBtn, { backgroundColor: cores.card }]} onPress={() => router.back()}>
            <Ionicons name="arrow-back" size={22} color={cores.texto} />
          </TouchableOpacity>
          <Text style={[styles.headerTitle, { color: cores.texto }]}>Ficha de Aluno</Text>
          <TouchableOpacity 
            style={[styles.roundBtn, { backgroundColor: isEditing ? cores.azul : cores.card }]} 
            onPress={() => isEditing ? salvarDados() : setIsEditing(true)}
            disabled={saving}
          >
            {saving ? <ActivityIndicator size="small" color="#fff" /> : <Ionicons name={isEditing ? "checkmark-sharp" : "create-outline"} size={22} color={isEditing ? "#fff" : cores.azul} />}
          </TouchableOpacity>
        </View>

        <ScrollView 
          contentContainerStyle={styles.scrollContainer} 
          showsVerticalScrollIndicator={false}
          refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={[cores.azul]} tintColor={cores.azul} />}
        >
          <Animated.View style={{ opacity: fadeAnim }}>
            
            <View style={styles.avatarSection}>
              <View style={[styles.avatarCircle, { backgroundColor: cores.azul }]}>
                <Text style={styles.avatarInitial}>{perfil?.nome?.charAt(0)?.toUpperCase() || '?'}</Text>
              </View>
              <TextInput 
                style={[styles.profileName, { color: cores.texto, borderBottomWidth: isEditing ? 1 : 0, borderBottomColor: cores.borda }]}
                value={perfil?.nome}
                editable={isEditing}
                onChangeText={(v) => setPerfil({...perfil, nome: v})}
                placeholder="Nome do Aluno"
                placeholderTextColor={cores.secundario}
              />
              <View style={[styles.badge, { backgroundColor: cores.azulSuave }]}>
                <Text style={[styles.badgeText, { color: cores.azul }]}>{perfil?.turma_curso || 'CURSO NÃO DEFINIDO'}</Text>
              </View>
            </View>

            <Text style={[styles.sectionHeader, { color: cores.secundario }]}>Registo Escolar</Text>
            <View style={[styles.infoCard, { backgroundColor: cores.card }]}>
              <View style={styles.inputRow}>
                <View style={{ flex: 1, marginRight: 10 }}>
                  <PerfilInput label="Nº Escola" icon="id-card-outline" value={perfil?.n_escola?.toString() || 'N/A'} editable={false} cores={cores} />
                </View>
                <View style={{ flex: 1 }}>
                  <PerfilInput label="Ano" icon="calendar-outline" value={perfil?.ano ? `${perfil.ano}º Ano` : 'N/A'} editable={false} cores={cores} />
                </View>
              </View>
              <PerfilInput label="Email Institucional" icon="mail-outline" value={perfil?.email} editable={false} cores={cores} />
            </View>

            <Text style={[styles.sectionHeader, { color: cores.secundario }]}>Dados Pessoais</Text>
            <View style={[styles.infoCard, { backgroundColor: cores.card }]}>
              <PerfilInput 
                label="Data Nascimento" icon="gift-outline" 
                value={perfil?.data_nascimento} 
                editable={isEditing} 
                onChangeText={(v:string) => {
                  const masked = aplicarMascaraData(v);
                  const novaIdade = calcularIdade(masked);
                  setPerfil({...perfil, data_nascimento: masked, idade: novaIdade ?? 'N/A'});
                }} 
                cores={cores} 
                placeholder="DD-MM-AAAA"
                maxLength={10}
              />
              <View style={styles.inputRow}>
                <View style={{ flex: 1, marginRight: 10 }}>
                  <PerfilInput label="Idade" icon="time-outline" value={perfil?.idade?.toString()} editable={false} cores={cores} />
                </View>
                <View style={{ flex: 2 }}>
                  <PerfilInput label="Telemóvel" icon="call-outline" value={perfil?.telefone} editable={isEditing} onChangeText={(v:string) => setPerfil({...perfil, telefone: v})} cores={cores} keyboardType="phone-pad" />
                </View>
              </View>
              <PerfilInput label="Residência" icon="location-outline" value={perfil?.residencia} editable={isEditing} onChangeText={(v:string) => setPerfil({...perfil, residencia: v})} cores={cores} />
            </View>

            <View style={styles.footer}>
              <TouchableOpacity style={[styles.actionMenuItem, { backgroundColor: cores.card }]} onPress={() => router.push('/redefenirsenha')}>
                <View style={[styles.actionIcon, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="lock-closed-outline" size={20} color={cores.azul} />
                </View>
                <Text style={[styles.actionText, { color: cores.texto }]}>Alterar palavra-passe</Text>
                <Ionicons name="chevron-forward" size={18} color={cores.borda} />
              </TouchableOpacity>

              <TouchableOpacity 
                style={[styles.actionMenuItem, { backgroundColor: cores.card, marginTop: 12, marginBottom: 50 }]} 
                onPress={() => supabase.auth.signOut().then(() => router.replace('/'))}
              >
                <View style={[styles.actionIcon, { backgroundColor: cores.vermelhoSuave }]}>
                  <Ionicons name="log-out-outline" size={20} color={cores.vermelho} />
                </View>
                <Text style={[styles.actionText, { color: cores.vermelho }]}>Terminar Sessão</Text>
              </TouchableOpacity>
            </View>

          </Animated.View>
        </ScrollView>
      </SafeAreaView>
    </KeyboardAvoidingView>
  );
}

const PerfilInput = ({ label, icon, cores, editable, ...props }: any) => (
  <View style={styles.inputGroup}>
    <Text style={[styles.inputLabel, { color: cores.secundario }]}>{label}</Text>
    <View style={[styles.inputContainer, { backgroundColor: cores.fundo, borderColor: editable ? cores.azul : cores.borda, borderStyle: editable ? 'solid' : 'dashed' }]}>
      <Ionicons name={icon} size={18} color={cores.azul} style={{ marginHorizontal: 12 }} />
      <TextInput 
        {...props} 
        editable={editable} 
        style={[styles.textInput, { color: cores.texto }]} 
        placeholderTextColor={cores.secundario} 
      />
    </View>
  </View>
);

const styles = StyleSheet.create({
  centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  modernAlert: { position: 'absolute', left: 20, right: 20, flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 20, zIndex: 9999, elevation: 8, shadowColor: '#000', shadowOffset: { width: 0, height: 5 }, shadowOpacity: 0.2, shadowRadius: 10 },
  modernAlertText: { color: '#fff', fontWeight: '800', fontSize: 14, marginLeft: 10, flex: 1 },
  headerContainer: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 15 },
  headerTitle: { fontSize: 19, fontWeight: '900' },
  roundBtn: { width: 45, height: 45, borderRadius: 14, justifyContent: 'center', alignItems: 'center', elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4 },
  scrollContainer: { paddingHorizontal: 20 },
  avatarSection: { alignItems: 'center', marginVertical: 20 },
  avatarCircle: { width: 100, height: 100, borderRadius: 50, alignItems: 'center', justifyContent: 'center', elevation: 4, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.2, shadowRadius: 8 },
  avatarInitial: { color: '#fff', fontSize: 40, fontWeight: '800' },
  profileName: { fontSize: 24, fontWeight: '900', marginTop: 15, textAlign: 'center', width: '100%' },
  badge: { paddingHorizontal: 14, paddingVertical: 6, borderRadius: 10, marginTop: 8 },
  badgeText: { fontSize: 10, fontWeight: '900', letterSpacing: 1, textTransform: 'uppercase' },
  sectionHeader: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1.5, marginBottom: 12, marginTop: 25, marginLeft: 5 },
  infoCard: { borderRadius: 24, padding: 20, elevation: 3, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.05, shadowRadius: 10 },
  inputGroup: { marginBottom: 15 },
  inputLabel: { fontSize: 9, fontWeight: '900', textTransform: 'uppercase', marginBottom: 6, marginLeft: 4, letterSpacing: 0.5 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', borderRadius: 14, borderWidth: 1.5, height: 52 },
  textInput: { flex: 1, fontSize: 15, fontWeight: '700' },
  inputRow: { flexDirection: 'row', justifyContent: 'space-between' },
  footer: { marginTop: 25 },
  actionMenuItem: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 20, elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 1 }, shadowOpacity: 0.1, shadowRadius: 3 },
  actionIcon: { width: 40, height: 40, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  actionText: { flex: 1, marginLeft: 15, fontSize: 15, fontWeight: '800' }
});