// app/Professor/redefenirsenha2.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useCallback, useMemo, useRef, useState } from 'react';
import {
  ActivityIndicator,
  Animated,
  KeyboardAvoidingView,
  Platform,
  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';

export default function RedefinirSenhaInterna() {
  const router = useRouter();
  const { isDarkMode } = useTheme();
  const insets = useSafeAreaInsets();

  const [novaPassword, setNovaPassword] = useState('');
  const [confirmarPassword, setConfirmarPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [isFocused1, setIsFocused1] = useState(false);
  const [isFocused2, setIsFocused2] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

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

  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',
    placeholder: isDarkMode ? '#555' : '#94A3B8',
    verde: sucessoCor // 🟢 COR ADICIONADA AQUI
  }), [isDarkMode]);

  const showToast = useCallback((message: string, type: 'error' | 'success' = 'error') => {
    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: 'error' }));
      }, 3500);
    });
  }, [insets.top, slideAnim]);

  const handleUpdatePassword = async () => {
    if (!novaPassword || !confirmarPassword) {
      showToast("Preenche todos os campos!", 'error');
      return;
    }

    if (novaPassword.length < 6) {
      showToast("A palavra-passe tem de ter pelo menos 6 caracteres.", 'error');
      return;
    }

    if (novaPassword !== confirmarPassword) {
      showToast("As palavras-passe não coincidem.", 'error');
      return;
    }

    setLoading(true);
    try {
      const { error } = await supabase.auth.updateUser({ password: novaPassword });
      
      if (error) throw error;

      showToast("Palavra-passe atualizada com segurança!", 'success');
      
      setTimeout(() => router.back(), 2000);

    } catch (err: any) {
      showToast(err.message, 'error');
    } finally {
      setLoading(false);
    }
  };

  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: erroCor } : { backgroundColor: sucessoCor }
      ]}>
        <Ionicons name={toast.type === 'error' ? "warning" : "shield-checkmark"} size={24} color="#FFF" />
        <Text style={styles.toastText}>{toast.message}</Text>
      </Animated.View>

      <SafeAreaView style={styles.safe} edges={['top', 'left', 'right']}>
        <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={{ flex: 1 }}>
          
          <View style={styles.header}>
            <TouchableOpacity onPress={() => router.back()} style={[styles.backBtn, { 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 }]}>Segurança</Text>
              <Text style={[styles.headerSubtitle, { color: cores.laranja }]}>Estágios+</Text>
            </View>
            <View style={{ width: 44 }} />
          </View>

          <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">
            
            <View style={styles.heroSection}>
              <View style={[styles.iconShield, { backgroundColor: cores.azulSuave, borderColor: cores.azul }]}>
                <Ionicons name="lock-closed" size={42} color={cores.azul} />
                <View style={[styles.badgeVerificado, { backgroundColor: cores.verde }]}>
                  <Ionicons name="checkmark" size={12} color="#FFF" />
                </View>
              </View>
              <Text style={[styles.title, { color: cores.texto }]}>Alterar Palavra-passe</Text>
              <Text style={[styles.subtitle, { color: cores.secundario }]}>
                Cria uma palavra-passe forte para manteres a tua conta protegida.
              </Text>
            </View>

            <View style={styles.form}>
              
              <View style={styles.inputWrapper}>
                <Text style={[styles.label, { color: cores.secundario }, isFocused1 && { color: cores.azul }]}>Nova Palavra-passe</Text>
                <View style={[
                  styles.inputContainer, 
                  { backgroundColor: cores.inputFundo, borderColor: isFocused1 ? cores.azul : cores.borda }
                ]}>
                  <Ionicons name="key-outline" size={20} color={isFocused1 ? cores.azul : cores.secundario} style={{ marginRight: 10 }} />
                  <TextInput
                    style={[styles.input, { color: cores.texto }]}
                    placeholder="Mínimo de 6 caracteres"
                    placeholderTextColor={cores.placeholder}
                    value={novaPassword}
                    onChangeText={setNovaPassword}
                    onFocus={() => setIsFocused1(true)}
                    onBlur={() => setIsFocused1(false)}
                    secureTextEntry={!showPassword}
                    editable={!loading}
                  />
                  <TouchableOpacity onPress={() => setShowPassword(!showPassword)} style={{ padding: 5 }}>
                    <Ionicons name={showPassword ? "eye-off-outline" : "eye-outline"} size={20} color={cores.secundario} />
                  </TouchableOpacity>
                </View>
              </View>

              <View style={styles.inputWrapper}>
                <Text style={[styles.label, { color: cores.secundario }, isFocused2 && { color: cores.azul }]}>Confirmar Palavra-passe</Text>
                <View style={[
                  styles.inputContainer, 
                  { backgroundColor: cores.inputFundo, borderColor: isFocused2 ? cores.azul : cores.borda }
                ]}>
                  <Ionicons name="checkmark-done-outline" size={20} color={isFocused2 ? cores.azul : cores.secundario} style={{ marginRight: 10 }} />
                  <TextInput
                    style={[styles.input, { color: cores.texto }]}
                    placeholder="Repete a tua nova palavra-passe"
                    placeholderTextColor={cores.placeholder}
                    value={confirmarPassword}
                    onChangeText={setConfirmarPassword}
                    onFocus={() => setIsFocused2(true)}
                    onBlur={() => setIsFocused2(false)}
                    secureTextEntry={!showPassword}
                    editable={!loading}
                  />
                </View>
              </View>

              <TouchableOpacity
                activeOpacity={0.8}
                style={[styles.button, { backgroundColor: loading ? cores.secundario : cores.azul }]}
                onPress={handleUpdatePassword}
                disabled={loading}
              >
                {loading ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <Ionicons name="shield-checkmark" size={20} color="#FFF" style={{ marginRight: 8 }} />
                    <Text style={styles.buttonText}>Atualizar Palavra-passe</Text>
                  </View>
                )}
              </TouchableOpacity>
            </View>

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

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

  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 20, paddingVertical: 15 },
  backBtn: { width: 44, height: 44, borderRadius: 14, borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  headerTitle: { fontSize: 18, fontWeight: '900', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 11, fontWeight: '800', textTransform: 'uppercase', letterSpacing: 1, marginTop: 2 }, // 🟢 ESTILO ADICIONADO AQUI
  
  scrollContent: { paddingHorizontal: 28, paddingBottom: 40 },
  
  heroSection: { alignItems: 'center', marginTop: 30, marginBottom: 40 },
  iconShield: { width: 80, height: 80, borderRadius: 25, justifyContent: 'center', alignItems: 'center', borderWidth: 1.5, position: 'relative' },
  badgeVerificado: { position: 'absolute', bottom: -5, right: -5, width: 24, height: 24, borderRadius: 12, justifyContent: 'center', alignItems: 'center', borderWidth: 2, borderColor: '#FFF' },
  title: { fontSize: 26, fontWeight: '900', marginTop: 20, letterSpacing: -0.5 },
  subtitle: { fontSize: 14, textAlign: 'center', marginTop: 8, lineHeight: 22, fontWeight: '500' },

  form: { width: '100%' },
  inputWrapper: { marginBottom: 20 },
  label: { fontSize: 11, fontWeight: '900', textTransform: 'uppercase', marginBottom: 8, marginLeft: 4, letterSpacing: 0.5 },
  inputContainer: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, height: 56, borderRadius: 18, borderWidth: 1.5 },
  input: { flex: 1, fontSize: 15, fontWeight: '600' },
  
  button: { borderRadius: 18, height: 60, justifyContent: 'center', alignItems: 'center', marginTop: 15, elevation: 4, shadowColor: '#000', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.2, shadowRadius: 8 },
  buttonText: { color: '#fff', fontSize: 15, fontWeight: '900', letterSpacing: 1 },
});