// app/Definicoes.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { memo, useCallback, useMemo, useState } from 'react';
import {
  Animated,
  Linking,
  ScrollView,
  StatusBar,
  StyleSheet,
  Switch,
  Text,
  TouchableOpacity,
  View
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTheme } from '../../themecontext';
import { supabase } from '../lib/supabase';

const Definicoes = memo(() => {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const { isDarkMode, toggleTheme } = useTheme();
  const [notificacoes, setNotificacoes] = useState(true);

  // --- SISTEMA DE AVISOS MODERNOS ---
  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(2500),
      Animated.timing(alertOpacity, { toValue: 0, duration: 300, useNativeDriver: true })
    ]).start(() => setAlertConfig(null));
  }, []);

  const azulPetroleo = '#2390a6';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0F0F0F' : '#F1F5F9',
    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.08)',
    vermelho: '#EF4444',
    vermelhoSuave: 'rgba(239, 68, 68, 0.1)',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    verde: '#10B981',
  }), [isDarkMode]);

  const handleLogout = async () => {
    try {
      await supabase.auth.signOut();
      router.replace('/');
    } catch (e) {
      showAlert("Erro ao sair da conta", "error");
    }
  };

  const abrirURL = (url: string) => {
    Linking.canOpenURL(url).then(supported => {
      if (supported) Linking.openURL(url);
      else showAlert("Não foi possível abrir o link", "error");
    });
  };

  return (
    <View style={{ flex: 1, backgroundColor: cores.fundo }}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />

      {/* BANNER DE FEEDBACK */}
      {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" : "information-circle"} size={20} color="#fff" />
          <Text style={styles.alertText}>{alertConfig.msg}</Text>
        </Animated.View>
      )}

      <SafeAreaView style={styles.safe} edges={['top']}>
        
        {/* HEADER ESTILIZADO */}
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.btnVoltar, { backgroundColor: cores.card, borderColor: cores.borda }]} 
            onPress={() => router.back()}
          >
            <Ionicons name="chevron-back" size={24} color={cores.texto} />
          </TouchableOpacity>
          <Text style={[styles.tituloGeral, { color: cores.texto }]}>Definições</Text>
          <View style={{ width: 45 }} />
        </View>

        <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
          
          {/* GRUPO: PERSONALIZAÇÃO */}
          <Text style={[styles.sectionLabel, { color: cores.secundario }]}>Personalização</Text>
          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <View style={[styles.item, { borderBottomColor: cores.borda }]}>
              <View style={[styles.iconContainer, { backgroundColor: cores.azulSuave }]}>
                <Ionicons name="notifications" size={20} color={cores.azul} />
              </View>
              <Text style={[styles.itemTexto, { color: cores.texto }]}>Notificações Push</Text>
              <Switch
                value={notificacoes}
                onValueChange={(v) => {
                    setNotificacoes(v);
                    showAlert(v ? "Notificações ativadas" : "Notificações desativadas", "info");
                }}
                trackColor={{ false: '#CBD5E1', true: cores.azul }}
                thumbColor="#FFFFFF"
              />
            </View>

            <View style={styles.item}>
              <View style={[styles.iconContainer, { backgroundColor: isDarkMode ? '#334155' : '#F1F5F9' }]}>
                <Ionicons name={isDarkMode ? "moon" : "sunny"} size={20} color={isDarkMode ? '#FACC15' : '#F59E0B'} />
              </View>
              <Text style={[styles.itemTexto, { color: cores.texto }]}>Interface Escura</Text>
              <Switch
                value={isDarkMode}
                onValueChange={toggleTheme}
                trackColor={{ false: '#CBD5E1', true: cores.azul }}
                thumbColor="#FFFFFF"
              />
            </View>
          </View>

          {/* GRUPO: CONTACTOS EPVC */}
          <Text style={[styles.sectionLabel, { color: cores.secundario, marginTop: 25 }]}>Escola Profissional</Text>
          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <SettingLink 
                icon="business" 
                label="Direção Geral" 
                subLabel="epvc@epvc.pt" 
                onPress={() => abrirURL('mailto:epvc@epvc.pt')} 
                cores={cores}
                showBorder
            />
            <SettingLink 
                icon="mail" 
                label="Secretaria" 
                subLabel="secretaria@epvc.pt" 
                onPress={() => abrirURL('mailto:secretaria@epvc.pt')} 
                cores={cores}
                showBorder
            />
            <SettingLink 
                icon="call" 
                label="Linha Direta" 
                subLabel="252 641 805" 
                onPress={() => abrirURL('tel:252641805')} 
                cores={cores}
            />
          </View>

          {/* GRUPO: SEGURANÇA & INFO */}
          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda, marginTop: 25 }]}>
            <View style={[styles.item, { borderBottomColor: cores.borda }]}>
              <View style={[styles.iconContainer, { backgroundColor: cores.azulSuave }]}>
                <Ionicons name="shield-checkmark" size={20} color={cores.azul} />
              </View>
              <Text style={[styles.itemTexto, { color: cores.texto }]}>Versão Estável</Text>
              <Text style={[styles.versionBadge, { color: cores.secundario }]}>v2.6.17</Text>
            </View>

            <TouchableOpacity style={styles.item} onPress={handleLogout}>
              <View style={[styles.iconContainer, { backgroundColor: cores.vermelhoSuave }]}>
                <Ionicons name="log-out" size={20} color={cores.vermelho} />
              </View>
              <Text style={[styles.itemTexto, { color: cores.vermelho, fontWeight: '800' }]}>Terminar Sessão</Text>
              <Ionicons name="chevron-forward" size={18} color={cores.vermelho} opacity={0.5} />
            </TouchableOpacity>
          </View>

          <View style={styles.footer}>
            <Text style={[styles.footerText, { color: cores.secundario }]}>Desenvolvido para PAP • 2026</Text>
            <Text style={[styles.footerText, { color: cores.azul, fontWeight: '800', marginTop: 4 }]}>EPVC</Text>
          </View>

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

// Componente Auxiliar para Links
const SettingLink = ({ icon, label, subLabel, onPress, cores, showBorder }: any) => (
  <TouchableOpacity 
    style={[styles.item, showBorder && { borderBottomWidth: 1, borderBottomColor: cores.borda }]} 
    onPress={onPress}
  >
    <View style={[styles.iconContainer, { backgroundColor: cores.azulSuave }]}>
      <Ionicons name={icon} size={20} color={cores.azul} />
    </View>
    <View style={{ flex: 1, marginLeft: 15 }}>
      <Text style={[styles.itemTexto, { color: cores.texto, marginLeft: 0 }]}>{label}</Text>
      <Text style={{ color: cores.secundario, fontSize: 12, marginTop: 2 }}>{subLabel}</Text>
    </View>
    <Ionicons name="chevron-forward" size={18} color={cores.secundario} opacity={0.3} />
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  safe: { flex: 1 },
  alertBar: { position: 'absolute', left: 20, right: 20, padding: 15, borderRadius: 16, flexDirection: 'row', alignItems: 'center', zIndex: 9999, elevation: 8 },
  alertText: { color: '#fff', fontWeight: '700', marginLeft: 10, flex: 1, fontSize: 14 },
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 10 },
  btnVoltar: { width: 45, height: 45, borderRadius: 15, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  tituloGeral: { fontSize: 22, fontWeight: '900', letterSpacing: -0.5 },
  scrollContent: { paddingHorizontal: 20, paddingBottom: 50 },
  sectionLabel: { fontSize: 12, fontWeight: '800', textTransform: 'uppercase', marginBottom: 12, marginLeft: 8, letterSpacing: 1.2 },
  card: { borderRadius: 28, paddingHorizontal: 20, borderWidth: 1, shadowColor: '#000', shadowOpacity: 0.03, shadowRadius: 15, elevation: 2 },
  item: { flexDirection: 'row', alignItems: 'center', paddingVertical: 16 },
  iconContainer: { width: 42, height: 42, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  itemTexto: { flex: 1, marginLeft: 15, fontSize: 16, fontWeight: '700' },
  versionBadge: { fontSize: 13, fontWeight: 'bold', backgroundColor: 'rgba(0,0,0,0.05)', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 8 },
  footer: { alignItems: 'center', marginTop: 40, opacity: 0.6 },
  footerText: { fontSize: 11, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 1 }
});

export default Definicoes;