// app/forgot-password.tsx
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { useState } from 'react';
import {
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import { supabase } from '../app/lib/supabase';

export default function ForgotPassword() {
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  
  // ESTADOS PARA OS AVISOS MODERNOS
  const [status, setStatus] = useState<{ type: 'error' | 'success'; msg: string } | null>(null);

  const router = useRouter();

  const handleSendResetEmail = async () => {
    setStatus(null); // Limpa avisos anteriores

    if (!email) {
      setStatus({ type: 'error', msg: 'Por favor, insira o seu email corretamente.' });
      return;
    }

    setLoading(true);
    try {
      const { error } = await supabase.auth.resetPasswordForEmail(email);
      if (error) throw error;

      setStatus({ type: 'success', msg: 'Link enviado! Verifique ao seu email.' });
      
      // Espera 3 segundos para o utilizador ler e volta para o login
      setTimeout(() => router.back(), 3500);

    } catch (err: any) {
      setStatus({ type: 'error', msg: 'Não foi possível enviar o email. Tente novamente!' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.mainContainer}>
      <StatusBar barStyle="dark-content" backgroundColor="#FFFFFF" />
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      >
        <ScrollView 
          contentContainerStyle={styles.scrollContainer} 
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <TouchableOpacity 
            activeOpacity={0.7} 
            onPress={() => router.back()} 
            style={styles.backButtonTop}
          >
            <View style={styles.backIconCircle}>
              <Ionicons name="arrow-back" size={20} color="#1E293B" />
            </View>
            <Text style={styles.backButtonText}>Voltar</Text>
          </TouchableOpacity>

          <View style={styles.content}>
            <View style={styles.header}>
              <View style={styles.iconWrapper}>
                <View style={styles.iconCircle}>
                  <Ionicons name="mail-unread-outline" size={38} color="#2390a6" />
                </View>
                <View style={styles.iconBadge} />
              </View>
              
              <Text style={styles.title}>Não sabes a tua palavra-passe?</Text>
              <Text style={styles.subtitle}>
                Não te preocupes! Insere o teu email e enviaremos instruções para recuperares o acesso à nossa app.
              </Text>
            </View>

            {/* AVISOS/ERROS MODERNOS AQUI */}
            {status && (
              <View style={[styles.statusBanner, status.type === 'success' ? styles.successBg : styles.errorBg]}>
                <Ionicons 
                  name={status.type === 'success' ? "checkmark-circle" : "alert-circle"} 
                  size={20} 
                  color={status.type === 'success' ? "#059669" : "#EF4444"} 
                />
                <Text style={[styles.statusText, status.type === 'success' ? styles.successText : styles.errorText]}>
                  {status.msg}
                </Text>
              </View>
            )}

            <View style={styles.form}>
              <View style={styles.inputWrapper}>
                <Text style={[styles.label, isFocused && { color: '#2390a6' }]}>Email</Text>
                <TextInput
                  style={[
                    styles.input, 
                    isFocused && styles.inputFocused
                  ]}
                  placeholder="Insira o seu email"
                  placeholderTextColor="#94A3B8"
                  value={email}
                  onChangeText={(val) => {
                    setEmail(val);
                    if(status) setStatus(null); // Limpa o erro ao começar a digitar
                  }}
                  onFocus={() => setIsFocused(true)}
                  onBlur={() => setIsFocused(false)}
                  keyboardType="email-address"
                  autoCapitalize="none"
                  editable={!loading}
                />
              </View>

              <TouchableOpacity
                activeOpacity={0.8}
                style={[styles.button, loading && styles.buttonDisabled]}
                onPress={handleSendResetEmail}
                disabled={loading}
              >
                {loading ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <Text style={styles.buttonText}>Enviar Instruções</Text>
                )}
              </TouchableOpacity>
            </View>
          </View>

          <View style={styles.footer}>
            <Text style={styles.footerText}>EPVC Estágios+ • 2026</Text>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </View>
  );
}

const styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  scrollContainer: { 
    flexGrow: 1, 
    paddingHorizontal: 28,
    paddingTop: Platform.OS === 'android' ? (StatusBar.currentHeight ?? 0) + 20 : 60,
    paddingBottom: 40,
  },
  backButtonTop: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'flex-start',
    marginBottom: 30,
  },
  backIconCircle: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: '#F8FAFC',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10,
    borderWidth: 1,
    borderColor: '#F1F5F9',
  },
  backButtonText: {
    fontSize: 15,
    color: '#64748B',
    fontWeight: '600',
  },
  content: {
    flex: 1,
    justifyContent: 'center',
  },
  header: {
    alignItems: 'center',
    marginBottom: 35,
  },
  iconWrapper: {
    position: 'relative',
    marginBottom: 20,
  },
  iconCircle: {
    width: 90,
    height: 90,
    backgroundColor: '#F0F7FF',
    borderRadius: 30,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#DBEAFE',
  },
  iconBadge: {
    position: 'absolute',
    bottom: -4,
    right: -4,
    width: 20,
    height: 20,
    borderRadius: 10,
    backgroundColor: '#2390a6',
    borderWidth: 3,
    borderColor: '#FFFFFF',
  },
  title: { 
    fontSize: 28, 
    fontWeight: '900', 
    color: '#0F172A', 
    textAlign: 'center',
    letterSpacing: -1,
  },
  subtitle: { 
    fontSize: 15, 
    color: '#64748B', 
    textAlign: 'center', 
    marginTop: 10,
    lineHeight: 22,
    maxWidth: 300,
  },
  // ESTILOS DOS BANNERS MODERNOS
  statusBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderRadius: 16,
    marginBottom: 25,
    borderWidth: 1,
  },
  statusText: {
    fontSize: 14,
    fontWeight: '600',
    marginLeft: 10,
    flex: 1,
  },
  errorBg: { backgroundColor: '#FEF2F2', borderColor: '#FEE2E2' },
  errorText: { color: '#B91C1C' },
  successBg: { backgroundColor: '#F0FDF4', borderColor: '#DCFCE7' },
  successText: { color: '#166534' },

  form: {
    width: '100%',
  },
  inputWrapper: {
    marginBottom: 24,
  },
  label: {
    fontSize: 14,
    fontWeight: '700',
    color: '#475569',
    marginBottom: 10,
    marginLeft: 4,
  },
  input: {
    backgroundColor: '#FBFDFF',
    borderRadius: 18,
    paddingHorizontal: 20,
    paddingVertical: 18,
    fontSize: 16,
    color: '#0F172A',
    borderWidth: 1.5,
    borderColor: '#F1F5F9',
  },
  inputFocused: {
    borderColor: '#2390a6',
    backgroundColor: '#FFFFFF',
  },
  button: {
    backgroundColor: '#dd8707',
    borderRadius: 18,
    paddingVertical: 20,
    alignItems: 'center',
    shadowColor: '#dd8707',
    shadowOffset: { width: 0, height: 6 },
    shadowOpacity: 0.3,
    shadowRadius: 10,
    elevation: 6,
  },
  buttonDisabled: { 
    backgroundColor: '#E2E8F0',
    elevation: 0,
  },
  buttonText: { 
    color: '#fff', 
    fontSize: 16, 
    fontWeight: '800',
  },
  footer: {
    marginTop: 40,
    alignItems: 'center',
  },
  footerText: {
    fontSize: 12,
    color: '#CBD5E1',
    fontWeight: '600',
  },
});