// app/Definicoes.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { memo, useCallback, useMemo, useRef, 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 { supabase } from '../../lib/supabase';
import { useTheme } from '../../themecontext';

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

  // TOAST ANIMADO UNIVERSAL
  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 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]);

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

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#F4F7FA', // Novo design Premium
    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',
    vermelho: erroCor,
    verde: sucessoCor,
    vermelhoSuave: isDarkMode ? 'rgba(239, 68, 68, 0.15)' : '#FEE2E2',
  }), [isDarkMode]);

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

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

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

      {/* 🟢 TOAST ANIMADO NO TOPO */}
      <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={styles.safe} edges={['top', 'left', 'right']}>
        
        {/* HEADER MODERNO */}
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.btnVoltar, { borderColor: cores.borda, backgroundColor: cores.card }]} 
            onPress={() => router.back()}
          >
            <Ionicons name="chevron-back" size={24} color={cores.azul} />
          </TouchableOpacity>
          <View style={{alignItems: 'center'}}>
            <Text style={[styles.tituloGeral, { color: cores.texto }]}>Definições</Text>
            <Text style={[styles.tituloSub, { color: cores.laranja }]}>Sistema & Suporte</Text>
          </View>
          <View style={{ width: 44 }} />
        </View>

        <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
          
          <Text style={[styles.sectionLabel, { color: cores.secundario }]}>Preferências</Text>
          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda }]}>
            <View style={[styles.item, { borderBottomWidth: 1, borderBottomColor: cores.borda }]}>
              <View style={[styles.iconContainer, { backgroundColor: cores.azulSuave }]}>
                <Ionicons name="notifications-outline" size={20} color={cores.azul} />
              </View>
              <Text style={[styles.itemTexto, { color: cores.texto }]}>Notificações</Text>
              <Switch
                value={notificacoes}
                onValueChange={(v) => {
                    setNotificacoes(v);
                    showToast(v ? "Notificações ligadas" : "Notificações desligadas", "info");
                }}
                trackColor={{ false: cores.borda, true: cores.laranja }}
                thumbColor="#FFFFFF"
              />
            </View>

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

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

          <View style={[styles.card, { backgroundColor: cores.card, borderColor: cores.borda, marginTop: 30 }]}>
            <View style={[styles.item, { borderBottomWidth: 1, borderBottomColor: cores.borda }]}>
              <View style={[styles.iconContainer, { backgroundColor: cores.azulSuave }]}>
                <Ionicons name="code-working-outline" size={20} color={cores.azul} />
              </View>
              <Text style={[styles.itemTexto, { color: cores.texto }]}>App Version</Text>
              <Text style={[styles.versionBadge, { color: cores.azul, backgroundColor: cores.azulSuave }]}>2.6.17</Text>
            </View>

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

          <View style={styles.footer}>
            <View style={[styles.footerLine, { backgroundColor: cores.laranja }]} />
            <Text style={[styles.footerText, { color: cores.secundario }]}>Estágios+ • Vila do Conde</Text>
            <Text style={[styles.footerText, { color: cores.azul, marginTop: 4, fontSize: 13 }]}>EPVC</Text>
          </View>

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

const SettingLink = ({ icon, label, subLabel, onPress, cores, showBorder }: any) => (
  <TouchableOpacity 
    style={[styles.item, showBorder && { borderBottomWidth: 1, borderBottomColor: cores.borda }]} 
    onPress={onPress}
    activeOpacity={0.7}
  >
    <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, fontWeight: '600' }}>{subLabel}</Text>
    </View>
    <View style={[styles.arrowCircle, { borderColor: cores.borda, backgroundColor: cores.fundo }]}>
      <Ionicons name="chevron-forward" size={14} color={cores.azul} />
    </View>
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  safe: { flex: 1 },
  // TOAST STYLES
  toastContainer: { position: 'absolute', left: 20, right: 20, zIndex: 9999, 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 },
  btnVoltar: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  tituloGeral: { fontSize: 20, fontWeight: '900', letterSpacing: -0.5 },
  tituloSub: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2 },
  
  scrollContent: { paddingHorizontal: 20, paddingTop: 10, paddingBottom: 60 },
  sectionLabel: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', marginBottom: 12, marginLeft: 8, letterSpacing: 0.8 },
  
  card: { borderRadius: 28, paddingHorizontal: 20, borderWidth: 1, elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.03, shadowRadius: 8 },
  item: { flexDirection: 'row', alignItems: 'center', paddingVertical: 18 },
  iconContainer: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  itemTexto: { flex: 1, marginLeft: 15, fontSize: 16, fontWeight: '800', letterSpacing: -0.3 },
  versionBadge: { fontSize: 12, fontWeight: '900', paddingHorizontal: 12, paddingVertical: 6, borderRadius: 10 },
  arrowCircle: { width: 34, height: 34, borderRadius: 12, borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  
  footer: { alignItems: 'center', marginTop: 50 },
  footerLine: { width: 40, height: 4, borderRadius: 2, marginBottom: 15 },
  footerText: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1.5 }
});

export default Definicoes;