// app/Aluno/AlunoHome.tsx
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect } from '@react-navigation/native';
import { decode } from 'base64-arraybuffer';
import * as DocumentPicker from 'expo-document-picker';
import * as FileSystem from 'expo-file-system/legacy';
import * as Location from 'expo-location';
import { useRouter } from 'expo-router';
import { memo, useCallback, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Animated,
  Modal,
  Platform,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from 'react-native';
import { Calendar, LocaleConfig } from 'react-native-calendars';
import { useTheme } from '../../themecontext';
import { supabase } from '../lib/supabase';

// Configuração PT-PT para o Calendário
LocaleConfig.locales['pt'] = {
  monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
  monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
  dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
  dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'],
};
LocaleConfig.defaultLocale = 'pt';

const getFeriadosMap = (ano: number) => ({
  [`${ano}-01-01`]: "Ano Novo", [`${ano}-04-25`]: "Dia da Liberdade",
  [`${ano}-05-01`]: "Dia do Trabalhador", [`${ano}-06-10`]: "Dia de Portugal",
  [`${ano}-06-24`]: "São João (Vila do Conde)", [`${ano}-08-15`]: "Assunção de Nª Senhora",
  [`${ano}-10-05`]: "Implantação da República", [`${ano}-11-01`]: "Todos os Santos",
  [`${ano}-12-01`]: "Restauração da Independência", [`${ano}-12-08`]: "Imaculada Conceição",
  [`${ano}-12-25`]: "Natal"
});

const AlunoHome = memo(() => {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const hojeStr = new Date().toISOString().split('T')[0];

  const [selectedDate, setSelectedDate] = useState(hojeStr);
  const [configEstagio, setConfigEstagio] = useState({ inicio: '', fim: '' });
  const [presencas, setPresencas] = useState<Record<string, boolean>>({});
  const [faltas, setFaltas] = useState<Record<string, boolean>>({});
  const [sumarios, setSumarios] = useState<Record<string, string>>({});
  const [urlsJustificacao, setUrlsJustificacao] = useState<Record<string, string>>({});
  
  const [pdf, setPdf] = useState<any>(null);
  const [editandoSumario, setEditandoSumario] = useState(false);
  const [isLoadingDB, setIsLoadingDB] = useState(true);
  const [isLocating, setIsLocating] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [showLocationModal, setShowLocationModal] = useState(false);
  const [alertConfig, setAlertConfig] = useState<{ msg: string, type: 'success' | 'error' | 'info' } | null>(null);
  const alertOpacity = useMemo(() => new Animated.Value(0), []);

  const azulPetroleo = '#2390a6';
  const laranjaEPVC = '#dd8707';

  const themeStyles = useMemo(() => ({
    fundo: isDarkMode ? '#0F0F0F' : '#F8FAFC',
    card: isDarkMode ? '#1A1A1A' : '#FFFFFF',
    texto: isDarkMode ? '#F8FAFC' : '#1E293B',
    textoSecundario: isDarkMode ? '#94A3B8' : '#64748B',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    azul: azulPetroleo,
    vermelho: '#EF4444',
    verde: '#10B981',
    aviso: isDarkMode ? '#2D2200' : '#FFF9E6',
    avisoTexto: isDarkMode ? '#FFD700' : '#856404'
  }), [isDarkMode]);

  const showAlert = (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));
  };

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

  const fetchDadosSupabase = async () => {
    setIsLoadingDB(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) return;
      const { data: estagio } = await supabase.from('estagios').select('data_inicio, data_fim').eq('aluno_id', user.id).single();
      
      if (estagio) {
        setConfigEstagio({ inicio: estagio.data_inicio, fim: estagio.data_fim });
      } else {
        setConfigEstagio({ inicio: '', fim: '' });
      }

      const { data, error } = await supabase.from('presencas').select('*').eq('aluno_id', user.id);
      if (error) throw error;
      const p: any = {}, f: any = {}, s: any = {}, u: any = {};
      data?.forEach(item => {
        if (item.estado === 'presente') { p[item.data] = true; s[item.data] = item.sumario || ''; }
        else { f[item.data] = true; u[item.data] = item.justificacao_url || ''; }
      });
      setPresencas(p); setFaltas(f); setSumarios(s); setUrlsJustificacao(u);
    } catch (error) { 
        console.error(error); 
    } finally { 
        setIsLoadingDB(false); 
    }
  };

  const feriadosMap = useMemo(() => getFeriadosMap(new Date(selectedDate).getFullYear()), [selectedDate]);
  
  // LOGICA CORRIGIDA: Se as datas forem '', o estágio não existe e bloqueia tudo
  const infoData = useMemo(() => {
    const data = new Date(selectedDate);
    const diaSemana = data.getDay(); 
    const nomeFeriado = feriadosMap[selectedDate];
    
    const temEstagio = configEstagio.inicio !== '' && configEstagio.fim !== '';
    const antesDoInicio = temEstagio && selectedDate < configEstagio.inicio;
    const depoisDoFim = temEstagio && selectedDate > configEstagio.fim;

    return { 
      valida: temEstagio && diaSemana !== 0 && diaSemana !== 6 && !antesDoInicio && !depoisDoFim && !nomeFeriado, 
      podeMarcar: temEstagio && selectedDate === hojeStr && !antesDoInicio && !depoisDoFim && !nomeFeriado,
      nomeFeriado, 
      antesDoInicio, 
      depoisDoFim, 
      foraDeRange: !temEstagio || antesDoInicio || depoisDoFim,
      temEstagio
    };
  }, [selectedDate, configEstagio, hojeStr, feriadosMap]);

  const handlePresencaClick = async () => {
    if (!infoData.temEstagio) {
        showAlert("Aguarde pela configuração do estágio.", "error");
        return;
    }
    const { status } = await Location.getForegroundPermissionsAsync();
    if (status === 'granted') {
      executarMarcacao();
    } else {
      setShowLocationModal(true);
    }
  };

  const executarMarcacao = async () => {
    setShowLocationModal(false);
    setIsLocating(true);
    try {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') throw new Error("Sem acesso ao GPS.");
      const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced });
      const { data: { user } } = await supabase.auth.getUser();
      await supabase.from('presencas').upsert({
        aluno_id: user?.id, data: selectedDate, estado: 'presente', lat: loc.coords.latitude, lng: loc.coords.longitude
      });
      showAlert("Presença marcada!", "success");
      fetchDadosSupabase();
    } catch (e: any) { showAlert(e.message, "error"); } 
    finally { setIsLocating(false); }
  };

  const handleFalta = async () => {
    if (infoData.foraDeRange) return showAlert("Data fora do período de estágio.", "error");
    if (!infoData.valida) return showAlert("Não é possível registar falta hoje.", "error");
    try {
      const { data: { user } } = await supabase.auth.getUser();
      await supabase.from('presencas').upsert({ aluno_id: user?.id, data: selectedDate, estado: 'faltou' });
      showAlert("Falta registada.", "info");
      fetchDadosSupabase();
    } catch (e) { showAlert("Erro ao registar falta.", "error"); }
  };

  const selecionarDocumento = async () => {
    const res = await DocumentPicker.getDocumentAsync({ type: 'application/pdf' });
    if (!res.canceled) setPdf(res.assets[0]);
  };

  const enviarJustificativo = async () => {
    if (!pdf) return;
    setIsUploading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      const fileBase64 = await FileSystem.readAsStringAsync(pdf.uri, { encoding: FileSystem.EncodingType.Base64 });
      const fileName = `${user?.id}/${selectedDate}_justificacao.pdf`;
      const { error: uploadError } = await supabase.storage.from('justificacoes').upload(fileName, decode(fileBase64), { contentType: 'application/pdf', upsert: true });
      if (uploadError) throw uploadError;
      const { data: { publicUrl } } = supabase.storage.from('justificacoes').getPublicUrl(fileName);
      await supabase.from('presencas').update({ justificacao_url: publicUrl }).match({ aluno_id: user?.id, data: selectedDate });
      setPdf(null);
      showAlert("Enviado com sucesso!", "success");
      fetchDadosSupabase();
    } catch (e) { showAlert("Erro no upload.", "error"); }
    finally { setIsUploading(false); }
  };

  const guardarSumario = async () => {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      await supabase.from('presencas').update({ sumario: sumarios[selectedDate] }).match({ aluno_id: user?.id, data: selectedDate });
      setEditandoSumario(false);
      showAlert("Sumário guardado!", "success");
      fetchDadosSupabase();
    } catch (e) { showAlert("Erro ao guardar.", "error"); }
  };

  return (
    <SafeAreaView style={[styles.safeArea, { backgroundColor: themeStyles.fundo }]}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />

      <Modal visible={showLocationModal} transparent animationType="slide">
        <View style={styles.modalOverlay}>
          <View style={[styles.locationModal, { backgroundColor: themeStyles.card }]}>
            <View style={styles.modalHandle} />
            <View style={[styles.iconCircle, { backgroundColor: azulPetroleo + '15' }]}>
              <Ionicons name="location" size={40} color={azulPetroleo} />
            </View>
            <Text style={[styles.modalTitle, { color: themeStyles.texto }]}>Confirmar Local</Text>
            <Text style={[styles.modalDesc, { color: themeStyles.textoSecundario }]}>
              Precisamos de validar a tua localização para confirmar que estás no estágio.
            </Text>
            <TouchableOpacity style={[styles.btnConfirmar, { backgroundColor: azulPetroleo }]} onPress={executarMarcacao}>
              <Text style={styles.txtBtn}>Confirmar e Marcar</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.btnFechar} onPress={() => setShowLocationModal(false)}>
              <Text style={[styles.txtFechar, { color: themeStyles.textoSecundario }]}>Cancelar</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      {alertConfig && (
        <Animated.View style={[styles.alertBar, { opacity: alertOpacity, backgroundColor: alertConfig.type === 'error' ? '#EF4444' : azulPetroleo }]}>
          <Text style={styles.alertText}>{alertConfig.msg}</Text>
        </Animated.View>
      )}

      <ScrollView contentContainerStyle={styles.container} showsVerticalScrollIndicator={false}>
        <View style={styles.topBar}>
          <Text style={[styles.title, { color: themeStyles.texto }]}>Estágios+</Text>
          <View style={styles.topIcons}>
            <TouchableOpacity onPress={() => router.push('/Aluno/definicoes')} style={{ marginRight: 15 }}>
              <Ionicons name="settings-outline" size={26} color={themeStyles.texto} />
            </TouchableOpacity>
            <TouchableOpacity onPress={() => router.push('/Aluno/perfil')}>
              <Ionicons name="person-circle-outline" size={30} color={themeStyles.texto} />
            </TouchableOpacity>
          </View>
        </View>

        {/* AVISO DE FALTA DE ESTÁGIO - Vai dar merda se o aluno não souber por que está bloqueado */}
        {!infoData.temEstagio && !isLoadingDB && (
            <View style={[styles.avisoBox, { backgroundColor: themeStyles.aviso }]}>
                <Ionicons name="alert-circle" size={20} color={themeStyles.avisoTexto} />
                <Text style={[styles.avisoTexto, { color: themeStyles.avisoTexto }]}>
                    O teu período de estágio ainda não foi configurado pelo professor.
                </Text>
            </View>
        )}

        <View style={styles.botoesLinha}>
          <TouchableOpacity 
            style={[
                styles.btn, 
                { backgroundColor: laranjaEPVC }, 
                (!infoData.podeMarcar || presencas[selectedDate] || faltas[selectedDate]) && styles.disabled
            ]} 
            onPress={handlePresencaClick}
            disabled={!infoData.podeMarcar || !!presencas[selectedDate] || !!faltas[selectedDate] || isLocating}
          >
            {isLocating ? <ActivityIndicator color="#fff" /> : <Text style={styles.txtBtn}>Marcar Presença</Text>}
          </TouchableOpacity>
          <TouchableOpacity 
            style={[
                styles.btn, 
                { backgroundColor: themeStyles.vermelho }, 
                (!infoData.valida || presencas[selectedDate] || faltas[selectedDate]) && styles.disabled
            ]} 
            onPress={handleFalta}
            disabled={!infoData.valida || !!presencas[selectedDate] || !!faltas[selectedDate]}
          >
            <Text style={styles.txtBtn}>Marcar Falta</Text>
          </TouchableOpacity>
        </View>

        <View style={[styles.cardCalendar, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda }]}>
          <Calendar
            key={isDarkMode ? 'dark' : 'light'} 
            minDate={configEstagio.inicio || undefined}
            maxDate={configEstagio.fim || undefined}
            theme={{ 
                calendarBackground: themeStyles.card, 
                dayTextColor: themeStyles.texto, 
                monthTextColor: themeStyles.texto, 
                todayTextColor: azulPetroleo, 
                selectedDayBackgroundColor: azulPetroleo,
                textDisabledColor: isDarkMode ? '#333' : '#DDD'
            }}
            markedDates={{
              ...Object.keys(feriadosMap).reduce((acc, d) => ({ ...acc, [d]: { marked: true, dotColor: azulPetroleo } }), {}),
              ...Object.keys(presencas).reduce((acc, d) => ({ ...acc, [d]: { marked: true, dotColor: '#10B981' } }), {}),
              ...Object.keys(faltas).reduce((acc, d) => ({ ...acc, [d]: { marked: true, dotColor: '#EF4444' } }), {}),
              [selectedDate]: { selected: true, selectedColor: azulPetroleo }
            }}
            onDayPress={(day) => setSelectedDate(day.dateString)}
          />
        </View>

        {presencas[selectedDate] && (
          <View style={[styles.card, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda }]}>
            <View style={styles.rowTitle}>
              <Text style={[styles.cardTitulo, { color: themeStyles.texto }]}>Sumário</Text>
              <TouchableOpacity onPress={() => setEditandoSumario(true)}><Ionicons name="create-outline" size={22} color={azulPetroleo} /></TouchableOpacity>
            </View>
            <TextInput
              style={[styles.input, { borderColor: themeStyles.borda, color: themeStyles.texto }]}
              multiline editable={editandoSumario}
              value={sumarios[selectedDate]}
              onChangeText={(txt) => setSumarios({...sumarios, [selectedDate]: txt})}
              placeholder="O que fizeste hoje?"
              placeholderTextColor="#94A3B8"
            />
            {editandoSumario && <TouchableOpacity style={[styles.btnSalvar, { backgroundColor: themeStyles.verde }]} onPress={guardarSumario}><Text style={styles.txtBtn}>Guardar Sumário</Text></TouchableOpacity>}
          </View>
        )}

        {faltas[selectedDate] && (
          <View style={[styles.card, { backgroundColor: themeStyles.card, borderColor: themeStyles.borda }]}>
            <Text style={[styles.cardTitulo, { color: themeStyles.texto, marginBottom: 15 }]}>Justificar</Text>
            {urlsJustificacao[selectedDate] ? (
              <View style={styles.justificadoBox}>
                <Ionicons name="checkmark-circle" size={20} color={themeStyles.verde} />
                <Text style={{ color: themeStyles.verde, fontWeight: '700' }}>Justificativo Enviado</Text>
              </View>
            ) : (
              <>
                <TouchableOpacity style={[styles.btnUpload, { borderColor: azulPetroleo }]} onPress={selecionarDocumento}>
                  <Ionicons name="document-attach-outline" size={20} color={azulPetroleo} />
                  <Text style={{ color: azulPetroleo, fontWeight: '600' }}>{pdf ? pdf.name : "Selecionar PDF"}</Text>
                </TouchableOpacity>
                {pdf && (
                  <TouchableOpacity style={[styles.btnSalvar, { backgroundColor: azulPetroleo }]} onPress={enviarJustificativo} disabled={isUploading}>
                    {isUploading ? <ActivityIndicator color="#fff" /> : <Text style={styles.txtBtn}>Submeter</Text>}
                  </TouchableOpacity>
                )}
              </>
            )}
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
});

const styles = StyleSheet.create({
  safeArea: { flex: 1, paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0 },
  container: { padding: 20 },
  topBar: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 25 },
  topIcons: { flexDirection: 'row', alignItems: 'center' },
  title: { fontSize: 26, fontWeight: '900' },
  alertBar: { position: 'absolute', top: 50, left: 20, right: 20, padding: 15, borderRadius: 15, zIndex: 1000 },
  alertText: { color: '#fff', fontWeight: 'bold', textAlign: 'center' },
  avisoBox: { flexDirection: 'row', alignItems: 'center', gap: 10, padding: 15, borderRadius: 15, marginBottom: 20 },
  avisoTexto: { fontSize: 13, fontWeight: '700', flex: 1 },
  botoesLinha: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 20 },
  btn: { padding: 18, borderRadius: 22, width: '48%', alignItems: 'center', elevation: 3 },
  txtBtn: { color: '#fff', fontWeight: '800', fontSize: 14 },
  disabled: { opacity: 0.3 },
  cardCalendar: { borderRadius: 30, padding: 10, borderWidth: 1, overflow: 'hidden' },
  card: { padding: 20, borderRadius: 25, marginTop: 20, borderWidth: 1 },
  cardTitulo: { fontSize: 18, fontWeight: '700' },
  rowTitle: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 15 },
  input: { borderWidth: 1, borderRadius: 15, padding: 15, height: 100, textAlignVertical: 'top' },
  btnSalvar: { padding: 15, borderRadius: 15, marginTop: 15, alignItems: 'center' },
  btnUpload: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10, padding: 15, borderRadius: 15, borderWidth: 2, borderStyle: 'dashed' },
  justificadoBox: { flexDirection: 'row', alignItems: 'center', gap: 8, padding: 10 },
  modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'flex-end' },
  locationModal: { borderTopLeftRadius: 40, borderTopRightRadius: 40, padding: 30, alignItems: 'center', paddingBottom: 50 },
  modalHandle: { width: 50, height: 6, backgroundColor: '#cbd5e1', borderRadius: 10, marginBottom: 30 },
  iconCircle: { width: 90, height: 90, borderRadius: 45, justifyContent: 'center', alignItems: 'center', marginBottom: 20 },
  modalTitle: { fontSize: 24, fontWeight: '800', marginBottom: 12 },
  modalDesc: { fontSize: 16, textAlign: 'center', lineHeight: 24, marginBottom: 35, paddingHorizontal: 15 },
  btnConfirmar: { width: '100%', padding: 18, borderRadius: 20, alignItems: 'center' },
  btnFechar: { marginTop: 20 },
  txtFechar: { fontWeight: '700', fontSize: 16 }
});

export default AlunoHome;