// app/Professor/Alunos/DetalhesAluno.tsx
import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  ActivityIndicator,
  Animated,
  Linking,
  Modal,
  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';

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 = (dataNascimento: string) => {
  if (!dataNascimento) return null;
  const hoje = new Date();
  const nascimento = new Date(dataNascimento);
  let idade = hoje.getFullYear() - nascimento.getFullYear();
  const m = hoje.getMonth() - nascimento.getMonth();
  if (m < 0 || (m === 0 && hoje.getDate() < nascimento.getDate())) {
    idade--;
  }
  return idade;
};

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

interface AlunoEditForm {
  nome: string;
  n_escola: string;
  turma_curso: string;
  telefone: string;
  residencia: string;
  data_nascimento: string;
  email: string;
}

const DetalhesAlunos = memo(() => {
  const router = useRouter();
  const params = useLocalSearchParams();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets();

  const alunoId = typeof params.alunoId === 'string' ? params.alunoId : null;
  const [aluno, setAluno] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [saving, setSaving] = useState(false);

  const [toast, setToast] = useState<{ visible: boolean; message: string; type: 'error' | 'success' | 'info' }>({ visible: false, message: '', type: 'info' });
  const slideAnim = useRef(new Animated.Value(-100)).current;

  const [editForm, setEditForm] = useState<AlunoEditForm>({
    nome: '', n_escola: '', turma_curso: '', telefone: '', residencia: '', data_nascimento: '', email: ''
  });

  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';
  const erroCor = '#EF4444';
  const sucessoCor = '#10B981';

  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',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    inputFundo: isDarkMode ? '#252525' : '#FBFDFF',
    vermelho: erroCor,
    verde: sucessoCor,
  }), [isDarkMode]);

  const showToast = useCallback((message: string, type: 'error' | 'success' | 'info' = 'info') => {
    setToast({ visible: true, message, type });
    Animated.timing(slideAnim, { toValue: insets.top + 10, duration: 300, useNativeDriver: true }).start(() => {
      setTimeout(() => {
        Animated.timing(slideAnim, { toValue: -100, duration: 300, useNativeDriver: true })
          .start(() => setToast({ visible: false, message: '', type: 'info' }));
      }, 3500);
    });
  }, [insets.top, slideAnim]);

  const fetchAluno = async () => {
    if (!alunoId) return;
    try {
      setLoading(true);
      
      const { data: alunoData, error: alunoError } = await supabase
        .from('alunos')
        .select(`*, estagios(*, empresas(*))`)
        .eq('id', alunoId)
        .single();

      if (alunoError) throw alunoError;

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

      let listaHorarios: string[] = [];
      const estagioAtivo = Array.isArray(alunoData.estagios) ? alunoData.estagios[0] : alunoData.estagios;

      if (estagioAtivo?.id) {
        const { data: hData } = await supabase
          .from('horarios_estagio')
          .select('*')
          .eq('estagio_id', estagioAtivo.id);
        if (hData) {
          listaHorarios = hData.map((h: any) => `${h.hora_inicio?.slice(0, 5)}h - ${h.hora_fim?.slice(0, 5)}h`);
        }
      }

      const infoCompleta = { ...alunoData, perfil: perfilData, estagio: estagioAtivo, horarios: listaHorarios };
      setAluno(infoCompleta);
      
      setEditForm({
        nome: alunoData.nome || '',
        n_escola: String(alunoData.n_escola || ''),
        turma_curso: alunoData.turma_curso || '',
        telefone: perfilData?.telefone || '',
        residencia: perfilData?.residencia || '',
        data_nascimento: formatarDataParaUI(perfilData?.data_nascimento) || '',
        email: perfilData?.email || ''
      });

    } catch (err: any) {
      console.error(err);
      showToast("Falha ao carregar os dados do aluno.", "error");
    } finally {
      setLoading(false);
    }
  };

  const handleUpdate = async () => {
    try {
      setSaving(true);
      
      const dataFormatadaDB = formatarDataParaDB(editForm.data_nascimento);
      const novaIdade = calcularIdade(dataFormatadaDB || '');

      const { data: d1, error: err1 } = await supabase.from('alunos').update({
        nome: editForm.nome,
        turma_curso: editForm.turma_curso
      }).eq('id', alunoId).select();

      const { data: d2, error: err2 } = await supabase.from('profiles').update({
        telefone: editForm.telefone,
        residencia: editForm.residencia,
        data_nascimento: dataFormatadaDB,
        idade: novaIdade
      }).eq('id', alunoId).select();

      if (err1) throw err1;
      if (err2) throw err2;

      if (!d1 || d1.length === 0 || !d2 || d2.length === 0) {
        throw new Error("Não tens permissões para editar este aluno.");
      }

      showToast("Dados atualizados com sucesso!", "success");
      setModalVisible(false);
      fetchAluno(); 
    } catch (err: any) {
      showToast(err.message || "Não foi possível guardar as alterações.", "error");
    } finally {
      setSaving(false);
    }
  };

  useEffect(() => { fetchAluno(); }, [alunoId]);

  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" />
      
      <Animated.View style={[
        styles.toastContainer, 
        { transform: [{ translateY: slideAnim }] },
        toast.type === 'error' ? { backgroundColor: cores.vermelho } : 
        toast.type === 'success' ? { backgroundColor: cores.verde } : 
        { backgroundColor: cores.azul }
      ]}>
        <Ionicons 
          name={toast.type === 'error' ? "warning" : toast.type === 'success' ? "checkmark-circle" : "information-circle"} 
          size={24} 
          color="#FFF" 
        />
        <Text style={styles.toastText}>{toast.message}</Text>
      </Animated.View>

      <SafeAreaView style={{ flex: 1 }} edges={['top', 'left', 'right']}>
        
        <View style={styles.header}>
          <TouchableOpacity onPress={() => router.back()} style={[styles.btnAction, { borderColor: cores.borda, backgroundColor: cores.card }]}>
            <Ionicons name="chevron-back" size={24} color={cores.azul} />
          </TouchableOpacity>
          <View style={{ alignItems: 'center' }}>
            <Text style={[styles.headerTitle, { color: cores.texto }]}>Ficha do Aluno</Text>
            <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>Estágios+</Text>
          </View>
          <TouchableOpacity onPress={() => setModalVisible(true)} style={[styles.btnAction, { borderColor: cores.borda, backgroundColor: cores.card }]}>
            <Ionicons name="pencil" size={20} color={cores.laranja} />
          </TouchableOpacity>
        </View>

        <ScrollView contentContainerStyle={[styles.scroll, { paddingBottom: insets.bottom + 30 }]} showsVerticalScrollIndicator={false}>
          
          <View style={styles.profileSection}>
            <View style={[styles.avatar, { backgroundColor: cores.azulSuave }]}>
              <Text style={[styles.avatarTxt, { color: cores.azul }]}>{aluno?.nome?.charAt(0)}</Text>
            </View>
            <View style={{ flex: 1 }}>
              <Text style={[styles.alunoNome, { color: cores.texto }]}>{aluno?.nome}</Text>
              <View style={[styles.roleBadge, { backgroundColor: cores.azulSuave }]}>
                <Ionicons name="school" size={12} color={cores.azul} style={{ marginRight: 4 }} />
                <Text style={[styles.alunoCurso, { color: cores.azul }]}>{aluno?.turma_curso}</Text>
              </View>
            </View>
          </View>

          <View style={[styles.infoCard, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <DetailRow icon="id-card" label="Nº Escola" value={aluno?.n_escola} cores={cores} />
            <DetailRow 
                icon="calendar" 
                label="Nascimento / Idade" 
                value={aluno?.perfil?.data_nascimento ? `${formatarDataParaUI(aluno.perfil.data_nascimento)} (${aluno.perfil.idade} anos)` : '-'} 
                cores={cores} 
            />
            <DetailRow 
              icon="mail" label="Email de Registo" value={aluno?.perfil?.email} cores={cores} 
              onPress={aluno?.perfil?.email ? () => Linking.openURL(`mailto:${aluno.perfil.email}`) : null} 
            />
            <DetailRow 
              icon="call" label="Contacto Telefónico" value={aluno?.perfil?.telefone} cores={cores} 
              onPress={aluno?.perfil?.telefone ? () => Linking.openURL(`tel:${aluno.perfil.telefone}`) : null} 
            />
            <DetailRow icon="home" label="Residência" value={aluno?.perfil?.residencia} cores={cores} ultimo />
          </View>

          <View style={styles.sectionHeader}>
            <Text style={[styles.sectionTitle, { color: cores.secundario }]}>Plano de Estágio</Text>
            <View style={[styles.sectionLine, { backgroundColor: cores.borda }]} />
          </View>

          {aluno?.estagio ? (
            <View style={[styles.estagioCard, { backgroundColor: cores.azul }]}>
              <View style={styles.estagioHeader}>
                <Ionicons name="business" size={28} color="rgba(255,255,255,0.4)" />
                <View style={styles.statusBadge}><Text style={styles.statusText}>ATIVO</Text></View>
              </View>
              <Text style={styles.empresaNome}>{aluno?.estagio?.empresas?.nome || 'Empresa'}</Text>
              
              <View style={styles.tutorInfo}>
                <Text style={styles.miniLabel}>TUTOR RESPONSÁVEL</Text>
                <Text style={styles.tutorNome}>{aluno?.estagio?.empresas?.tutor_nome || 'N/A'}</Text>
                <Text style={styles.tutorTel}>{aluno?.estagio?.empresas?.tutor_telefone || '-'}</Text>
              </View>

              <View style={styles.horarioBox}>
                <Text style={styles.miniLabel}>HORÁRIOS</Text>
                {aluno?.horarios?.length > 0 ? (
                  aluno.horarios.map((h: string, i: number) => <Text key={i} style={styles.horarioTxt}>{h}</Text>)
                ) : <Text style={styles.horarioTxt}>Não definido</Text>}
              </View>

              <View style={styles.estagioFooter}>
                <View style={styles.periodoCol}>
                   <Text style={styles.miniLabel}>DATA DE INÍCIO</Text>
                   <Text style={styles.footerVal}>{formatarDataParaUI(aluno?.estagio?.data_inicio) || '-'}</Text>
                </View>
                <View style={[styles.periodoCol, {alignItems: 'flex-end'}]}>
                   <Text style={styles.miniLabel}>DATA DE FIM</Text>
                   <Text style={styles.footerVal}>{formatarDataParaUI(aluno?.estagio?.data_fim) || '-'}</Text>
                </View>
              </View>
            </View>
          ) : (
            <View style={[styles.noEstagio, { borderColor: cores.borda, backgroundColor: cores.card }]}>
              <Ionicons name="alert-circle-outline" size={32} color={cores.secundario} style={{ marginBottom: 10 }} />
              <Text style={[styles.noEstagioTxt, { color: cores.secundario }]}>Nenhum estágio atribuído no momento</Text>
            </View>
          )}
        </ScrollView>

        <Modal visible={modalVisible} animationType="slide" transparent>
          <View style={styles.modalContainer}>
            <View style={[styles.modalContent, { backgroundColor: cores.fundo }]}>
              
              <View style={styles.modalHeader}>
                <View>
                  <Text style={[styles.modalTitle, { color: cores.texto }]}>Editar Aluno</Text>
                  <Text style={[styles.modalSubtitle, { color: cores.laranja }]}>Atualizar Informações</Text>
                </View>
                <TouchableOpacity onPress={() => setModalVisible(false)} style={[styles.closeBtn, { backgroundColor: cores.azulSuave }]}>
                  <Ionicons name="close" size={24} color={cores.azul} />
                </TouchableOpacity>
              </View>

              <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 40 }}>
                <EditInput label="Nome Completo" value={editForm.nome} onChange={(t: string) => setEditForm({...editForm, nome: t})} cores={cores} />
                
                <View style={{ flexDirection: 'row', gap: 10 }}>
                  <View style={{ flex: 1 }}>
                    <EditInput label="Nº Escola" value={editForm.n_escola} cores={cores} editable={false} />
                  </View>
                  <View style={{ flex: 1 }}>
                    <EditInput label="Turma/Curso" value={editForm.turma_curso} onChange={(t: string) => setEditForm({...editForm, turma_curso: t})} cores={cores} />
                  </View>
                </View>

                <EditInput label="Email de Registo" value={editForm.email} cores={cores} editable={false} />
                <EditInput label="Telemóvel" value={editForm.telefone} onChange={(t: string) => setEditForm({...editForm, telefone: t})} cores={cores} keyboard="phone-pad" />
                <EditInput 
                  label="Nascimento (DD-MM-AAAA)" 
                  value={editForm.data_nascimento} 
                  onChange={(t: string) => setEditForm({...editForm, data_nascimento: aplicarMascaraData(t)})} 
                  cores={cores} 
                  keyboard="numeric" 
                  maxLength={10} 
                />
                <EditInput label="Residência" value={editForm.residencia} onChange={(t: string) => setEditForm({...editForm, residencia: t})} cores={cores} />

                <TouchableOpacity onPress={handleUpdate} disabled={saving} style={[styles.btnSave, { backgroundColor: cores.azul }]}>
                  {saving ? <ActivityIndicator color="#fff" /> : <Text style={styles.btnSaveTxt}>Guardar Alterações</Text>}
                </TouchableOpacity>
              </ScrollView>
            </View>
          </View>
        </Modal>

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

interface EditInputProps {
  label: string;
  value: string;
  onChange?: (t: string) => void;
  cores: any;
  keyboard?: any;
  maxLength?: number;
  editable?: boolean;
}

const EditInput = ({ label, value, onChange, cores, keyboard = "default", maxLength, editable = true }: EditInputProps) => (
  <View style={{ marginBottom: 16 }}>
    <Text style={[styles.inputLabel, { color: cores.secundario }]}>{label}</Text>
    <TextInput 
      style={[
        styles.input, 
        { 
          backgroundColor: editable ? cores.inputFundo : cores.fundo, 
          color: editable ? cores.texto : cores.secundario, 
          borderColor: editable ? cores.azul : cores.borda,
          borderWidth: editable ? 1.5 : 1,
          opacity: editable ? 1 : 0.6
        }
      ]}
      value={value}
      onChangeText={onChange}
      keyboardType={keyboard}
      placeholderTextColor={cores.secundario}
      maxLength={maxLength}
      editable={editable}
    />
  </View>
);

const DetailRow = ({ icon, label, value, cores, ultimo, onPress }: any) => (
  <TouchableOpacity disabled={!onPress} onPress={onPress} activeOpacity={0.7} style={[styles.row, !ultimo && { borderBottomWidth: 1, borderBottomColor: cores.borda + '50' }]}>
    <View style={[styles.iconBox, { backgroundColor: cores.azulSuave }]}>
      <Ionicons name={icon} size={16} color={cores.azul} />
    </View>
    <View style={{ flex: 1, paddingRight: 10 }}>
      <Text style={[styles.rowLabel, { color: cores.secundario }]}>{label}</Text>
      <Text style={[styles.rowValue, { color: cores.texto }]}>{value || 'Não definido'}</Text>
    </View>
    {onPress && <Ionicons name="chevron-forward" size={16} color={cores.secundario} />}
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  toastContainer: { position: 'absolute', left: 20, right: 20, zIndex: 1000, flexDirection: 'row', alignItems: 'center', padding: 16, borderRadius: 16, elevation: 6, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.2, shadowRadius: 8 },
  toastText: { color: '#FFF', fontSize: 14, fontWeight: '700', marginLeft: 12, flex: 1 },

  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 15 },
  headerTitle: { fontSize: 18, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2 },
  btnAction: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  
  scroll: { paddingHorizontal: 24, paddingTop: 15 },
  
  profileSection: { flexDirection: 'row', alignItems: 'center', marginBottom: 30, gap: 16 },
  avatar: { width: 70, height: 70, borderRadius: 24, justifyContent: 'center', alignItems: 'center' },
  avatarTxt: { fontSize: 28, fontWeight: '900' },
  alunoNome: { fontSize: 22, fontWeight: '900', letterSpacing: -0.5, marginBottom: 6 },
  roleBadge: { flexDirection: 'row', alignItems: 'center', alignSelf: 'flex-start', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 8 },
  alunoCurso: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  
  infoCard: { borderRadius: 28, borderWidth: 1, paddingHorizontal: 20, paddingVertical: 8, marginBottom: 35, elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.03, shadowRadius: 8 },
  row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 14 },
  iconBox: { width: 32, height: 32, borderRadius: 10, justifyContent: 'center', alignItems: 'center', marginRight: 12 },
  rowLabel: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', marginBottom: 2, letterSpacing: 0.5 },
  rowValue: { fontSize: 15, fontWeight: '700' },
  
  sectionHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 15 },
  sectionTitle: { fontSize: 12, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 0.8, marginRight: 15 },
  sectionLine: { flex: 1, height: 1, opacity: 0.4 },
  
  estagioCard: { padding: 24, borderRadius: 28, elevation: 4, shadowColor: '#2390a6', shadowOffset: { width: 0, height: 6 }, shadowOpacity: 0.3, shadowRadius: 12 },
  estagioHeader: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 15 },
  statusBadge: { backgroundColor: 'rgba(255,255,255,0.2)', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 8 },
  statusText: { color: '#fff', fontSize: 10, fontWeight: '900', letterSpacing: 0.5 },
  empresaNome: { color: '#fff', fontSize: 22, fontWeight: '900', marginBottom: 18, letterSpacing: -0.5 },
  tutorInfo: { marginBottom: 18 },
  miniLabel: { color: 'rgba(255,255,255,0.6)', fontSize: 9, fontWeight: '900', letterSpacing: 0.5, marginBottom: 2 },
  tutorNome: { color: '#fff', fontSize: 16, fontWeight: '800' },
  tutorTel: { color: 'rgba(255,255,255,0.8)', fontSize: 13, fontWeight: '600' },
  horarioBox: { backgroundColor: 'rgba(255,255,255,0.1)', padding: 16, borderRadius: 18, marginBottom: 18 },
  horarioTxt: { color: '#fff', fontSize: 14, fontWeight: '700' },
  estagioFooter: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 5 },
  periodoCol: { flex: 1 },
  footerVal: { color: '#fff', fontSize: 14, fontWeight: '800', marginTop: 2 },
  
  noEstagio: { padding: 30, borderRadius: 24, borderWidth: 1, borderStyle: 'dashed', alignItems: 'center', justifyContent: 'center' },
  noEstagioTxt: { fontWeight: '700', fontSize: 15 },
  
  modalContainer: { flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'flex-end' },
  modalContent: { borderTopLeftRadius: 36, borderTopRightRadius: 36, padding: 25, maxHeight: '92%' },
  modalHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 25 },
  modalTitle: { fontSize: 22, fontWeight: '900', letterSpacing: -0.5 },
  modalSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2 },
  closeBtn: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  
  inputLabel: { fontSize: 10, fontWeight: '900', textTransform: 'uppercase', marginBottom: 8, marginLeft: 4, letterSpacing: 0.5 },
  input: { borderRadius: 16, paddingHorizontal: 16, height: 52, fontSize: 15, fontWeight: '700' },
  btnSave: { borderRadius: 18, height: 60, justifyContent: 'center', alignItems: 'center', marginTop: 20, elevation: 4, shadowColor: '#2390a6', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.3, shadowRadius: 8 },
  btnSaveTxt: { color: '#fff', fontWeight: '900', fontSize: 16, letterSpacing: 0.5 }
});

export default DetalhesAlunos;