// 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,
  KeyboardAvoidingView,
  Platform,
  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();
  
  // --- ESTADOS ---
  const [loading, setLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [perfil, setPerfil] = useState<any>(null);
  const [estagio, setEstagio] = useState<any>(null);
  const [saving, setSaving] = useState(false);

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

  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',
    sombra: isDarkMode ? 'rgba(0,0,0,0.5)' : 'rgba(0,0,0,0.05)',
  }), [isDarkMode]);

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

  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;
  };

  // --- CARREGAMENTO DE DADOS COM JOIN DE HORÁRIOS ---
  const buscarDados = async () => {
    try {
      setLoading(true);
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;

      const { data: pData } = await supabase.from('profiles').select('*').eq('id', user.id).single();
      
      let aData = {};
      if (pData?.n_escola) {
        const { data: alunoRes } = await supabase.from('alunos').select('*').eq('n_escola', pData.n_escola).single();
        if (alunoRes) aData = alunoRes;
      }

      // Join com a tabela horarios_estagio
      const { data: eData } = await supabase
        .from('estagios')
        .select(`
          *,
          empresas(nome, tutor_nome),
          horarios_estagio(periodo, hora_inicio, hora_fim)
        `)
        .eq('aluno_id', user.id)
        .maybeSingle();

      setPerfil({ ...pData, ...aData, email: user.email });
      setEstagio(eData);

      Animated.timing(fadeAnim, { toValue: 1, duration: 600, useNativeDriver: true }).start();
    } catch (err) {
      showAlert('Erro ao sincronizar dados.', 'error');
    } finally {
      setLoading(false);
    }
  };

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

  const salvarDados = async () => {
    try {
      setSaving(true);
      const { error } = await supabase.from('profiles').update({
        nome: perfil.nome,
        telefone: perfil.telefone,
        residencia: perfil.residencia,
        idade: perfil.idade,
        data_nascimento: perfil.data_nascimento
      }).eq('id', perfil.id);

      if (error) throw error;
      setIsEditing(false);
      showAlert('Perfil guardado!', 'success');
      buscarDados();
    } catch (e) {
      showAlert('Falha ao guardar.', 'error');
    } finally {
      setSaving(false);
    }
  };

  if (loading) 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.alert, { opacity: alertOpacity, backgroundColor: alertConfig.type === 'error' ? cores.vermelho : cores.verde, top: insets.top + 10 }]}>
          <Ionicons name="information-circle" size={20} color="#fff" />
          <Text style={styles.alertText}>{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}>
          <Animated.View style={{ opacity: fadeAnim }}>
            
            {/* CABEÇALHO */}
            <View style={styles.avatarSection}>
              <View style={[styles.avatarFrame, { borderColor: cores.azulSuave }]}>
                <View style={[styles.avatarCircle, { backgroundColor: cores.azul }]}>
                  <Text style={styles.avatarInitial}>{perfil?.nome?.charAt(0).toUpperCase()}</Text>
                </View>
              </View>
              <Text style={[styles.profileName, { color: cores.texto }]}>{perfil?.nome}</Text>
              <View style={[styles.badge, { backgroundColor: cores.azulSuave }]}>
                <Text style={[styles.badgeText, { color: cores.azul }]}>{perfil?.tipo?.toUpperCase()}</Text>
              </View>
            </View>

            {/* DADOS ESCOLARES */}
            <Text style={[styles.sectionHeader, { color: cores.secundario }]}>Registo Escolar</Text>
            <View style={[styles.infoCard, { backgroundColor: cores.card, shadowColor: cores.sombra }]}>
              <View style={styles.inputRow}>
                <View style={{ flex: 1, marginRight: 12 }}><PerfilInput label="Nº Escola" icon="id-card-outline" value={perfil?.n_escola?.toString()} editable={false} cores={cores} /></View>
                <View style={{ flex: 1 }}><PerfilInput label="Ano" icon="calendar-outline" value={perfil?.ano?.toString() + 'º Ano'} editable={false} cores={cores} /></View>
              </View>
              <PerfilInput label="Turma e Curso" icon="school-outline" value={perfil?.turma_curso} editable={false} cores={cores} />
            </View>

            {/* DADOS PESSOAIS */}
            <Text style={[styles.sectionHeader, { color: cores.secundario }]}>Contactos e Pessoal</Text>
            <View style={[styles.infoCard, { backgroundColor: cores.card, shadowColor: cores.sombra }]}>
              <PerfilInput label="Email" icon="mail-outline" value={perfil?.email} editable={false} cores={cores} />
              <View style={styles.inputRow}>
                <View style={{ flex: 0.8, marginRight: 12 }}><PerfilInput label="Idade" icon="time-outline" value={perfil?.idade?.toString()} editable={isEditing} onChangeText={(v:string) => setPerfil({...perfil, idade: v})} cores={cores} keyboardType="numeric" /></View>
                <View style={{ flex: 1.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" maxLength={9} /></View>
              </View>
              <PerfilInput label="Nascimento" icon="gift-outline" value={perfil?.data_nascimento} editable={isEditing} onChangeText={(v:string) => setPerfil({...perfil, data_nascimento: aplicarMascaraData(v)})} cores={cores} placeholder="DD-MM-AAAA" />
            </View>

            {/* SECÇÃO ESTÁGIO COM LOGICA DE HORARIOS RELACIONADOS */}
            {estagio && (
              <>
                <Text style={[styles.sectionHeader, { color: cores.secundario }]}>Informação de Estágio</Text>
                <View style={[styles.infoCard, { backgroundColor: cores.card, borderLeftWidth: 4, borderLeftColor: cores.azul, shadowColor: cores.sombra }]}>
                  <PerfilInput label="Empresa" icon="business-outline" value={estagio.empresas?.nome} editable={false} cores={cores} />
                  
                  <View style={styles.inputRow}>
                    <View style={{ flex: 1, marginRight: 12 }}>
                      <PerfilInput label="Horas" icon="timer-outline" value={estagio.horas_totais?.toString() + 'h'} editable={false} cores={cores} />
                    </View>
                    <View style={{ flex: 2 }}>
                      <PerfilInput 
                        label="Horário" 
                        icon="watch-outline" 
                        value={
                          estagio.horarios_estagio?.length > 0 
                            ? estagio.horarios_estagio.map((h: any) => 
                                `${h.periodo}: ${h.hora_inicio.slice(0,5)}-${h.hora_fim.slice(0,5)}`
                              ).join('\n')
                            : "Não definido"
                        } 
                        editable={false} 
                        cores={cores}
                        multiline={true} 
                      />
                    </View>
                  </View>
                  
                  {estagio.empresas?.tutor_nome && <PerfilInput label="Tutor" icon="person-circle-outline" value={estagio.empresas.tutor_nome} editable={false} cores={cores} />}
                </View>
              </>
            )}

            {/* ACÇÕES */}
            <View style={styles.footer}>
              <TouchableOpacity style={[styles.actionMenuItem, { backgroundColor: cores.card }]} onPress={() => router.push('/Aluno/redefenirsenha')}>
                <View style={[styles.actionIcon, { backgroundColor: cores.azulSuave }]}><Ionicons name="key-outline" size={20} color={cores.azul} /></View>
                <Text style={[styles.actionText, { color: cores.texto }]}>Redefinir Senha</Text>
                <Ionicons name="chevron-forward" size={18} color={cores.secundario} />
              </TouchableOpacity>
              <TouchableOpacity style={[styles.actionMenuItem, { backgroundColor: cores.card, marginTop: 12, marginBottom: 40 }]} 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, multiline, ...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,
      height: multiline ? undefined : 52,
      minHeight: 52,
      paddingVertical: multiline ? 8 : 0
    }]}>
      <Ionicons name={icon} size={18} color={cores.azul} style={{ marginHorizontal: 12, marginTop: multiline ? 10 : 0 }} />
      <TextInput 
        {...props} 
        editable={editable} 
        multiline={multiline}
        scrollEnabled={false}
        style={[styles.textInput, { color: cores.texto, textAlignVertical: multiline ? 'top' : 'center' }]} 
        placeholderTextColor={cores.secundario} 
      />
    </View>
  </View>
);

const styles = StyleSheet.create({
  centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  headerContainer: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 15 },
  headerTitle: { fontSize: 19, fontWeight: '900' },
  roundBtn: { width: 48, height: 48, borderRadius: 16, justifyContent: 'center', alignItems: 'center', elevation: 2 },
  scrollContainer: { paddingHorizontal: 20, paddingBottom: 20 },
  avatarSection: { alignItems: 'center', marginVertical: 25 },
  avatarFrame: { padding: 6, borderRadius: 100, borderWidth: 2, borderStyle: 'dashed' },
  avatarCircle: { width: 95, height: 95, borderRadius: 48, alignItems: 'center', justifyContent: 'center', elevation: 5 },
  avatarInitial: { color: '#fff', fontSize: 40, fontWeight: '800' },
  profileName: { fontSize: 24, fontWeight: '900', marginTop: 15 },
  badge: { paddingHorizontal: 12, paddingVertical: 4, borderRadius: 8, marginTop: 8 },
  badgeText: { fontSize: 11, fontWeight: '800', letterSpacing: 1 },
  sectionHeader: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1.5, marginLeft: 8, marginBottom: 12, marginTop: 15 },
  infoCard: { borderRadius: 25, padding: 20, elevation: 3, shadowOpacity: 0.1 },
  inputGroup: { marginBottom: 15 },
  inputLabel: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', marginBottom: 6, marginLeft: 4 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', borderRadius: 16, borderWidth: 1.5 },
  textInput: { flex: 1, fontSize: 14, fontWeight: '700' },
  inputRow: { flexDirection: 'row', justifyContent: 'space-between' },
  footer: { marginTop: 20 },
  actionMenuItem: { flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 22, elevation: 2 },
  actionIcon: { width: 42, height: 42, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  actionText: { flex: 1, marginLeft: 15, fontSize: 16, fontWeight: '800' },
  alert: { position: 'absolute', left: 20, right: 20, padding: 18, borderRadius: 20, flexDirection: 'row', alignItems: 'center', zIndex: 999 },
  alertText: { color: '#fff', fontWeight: '800', marginLeft: 10, flex: 1 }
});