// 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);

  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));
  }, []);

  // Cores EPVC
  const azulEPVC = '#2390a6';
  const laranjaEPVC = '#E38E00';

  const cores = useMemo(() => ({
    fundo: isDarkMode ? '#0A0A0A' : '#FFFFFF', // Branco puro do login
    card: isDarkMode ? '#161618' : '#F8FAFC',
    texto: isDarkMode ? '#F8FAFC' : '#1A365D',
    secundario: isDarkMode ? '#94A3B8' : '#718096',
    azul: azulEPVC,
    laranja: laranjaEPVC,
    azulSuave: isDarkMode ? 'rgba(35, 144, 166, 0.15)' : '#F0F9FA',
    vermelho: '#EF4444',
    vermelhoSuave: '#FFF5F5',
    borda: isDarkMode ? '#2D2D2D' : '#E2E8F0',
    verde: '#38A169',
  }), [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'} />

      {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']}>
        
        <View style={styles.header}>
          <TouchableOpacity 
            style={[styles.btnVoltar, { borderColor: cores.borda }]} 
            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: 45 }} />
        </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);
                    showAlert(v ? "Notificações ligadas" : "Notificações desligadas", "info");
                }}
                trackColor={{ false: '#CBD5E1', 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: '#CBD5E1', 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="Atendimento ao Docente" 
                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}>
              <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}
  >
    <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 }]}>
      <Ionicons name="chevron-forward" size={14} color={cores.azul} />
    </View>
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  safe: { flex: 1 },
  alertBar: { position: 'absolute', left: 20, right: 20, padding: 15, borderRadius: 12, flexDirection: 'row', alignItems: 'center', zIndex: 9999, elevation: 5 },
  alertText: { color: '#fff', fontWeight: '800', marginLeft: 10, flex: 1, fontSize: 13 },
  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 24, paddingVertical: 15 },
  btnVoltar: { width: 44, height: 44, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 1 },
  tituloGeral: { fontSize: 22, fontWeight: '900', letterSpacing: -0.5 },
  tituloSub: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 0.5 },
  scrollContent: { paddingHorizontal: 24, paddingBottom: 60 },
  sectionLabel: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', marginBottom: 15, marginLeft: 4, letterSpacing: 1 },
  card: { borderRadius: 28, paddingHorizontal: 20, borderWidth: 1, shadowColor: '#000', shadowOpacity: 0.02, shadowRadius: 10, elevation: 2 },
  item: { flexDirection: 'row', alignItems: 'center', paddingVertical: 18 },
  iconContainer: { width: 42, height: 42, borderRadius: 14, justifyContent: 'center', alignItems: 'center' },
  itemTexto: { flex: 1, marginLeft: 15, fontSize: 16, fontWeight: '700', letterSpacing: -0.2 },
  versionBadge: { fontSize: 11, fontWeight: '900', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 8 },
  arrowCircle: { width: 28, height: 28, borderRadius: 14, borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  footer: { alignItems: 'center', marginTop: 50 },
  footerLine: { width: 30, height: 3, borderRadius: 2, marginBottom: 15 },
  footerText: { fontSize: 10, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1.5 }
});

export default Definicoes;