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';
// CORREÇÃO 1: O caminho agora é ../lib/supabase porque moveste a pasta para a raiz
import { supabase } from '../lib/supabase';

// CORREÇÃO 2: O nome da função deve ser preferencialmente o nome do ficheiro
export default function NovaPasse() {
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  const [status, setStatus] = useState<{ type: 'error' | 'success'; msg: string } | null>(null);

  const router = useRouter();

  const handleUpdatePassword = async () => {
    setStatus(null);

    if (password.length < 6) {
      setStatus({ type: 'error', msg: 'A password deve ter pelo menos 6 caracteres.' });
      return;
    }

    if (password !== confirmPassword) {
      setStatus({ type: 'error', msg: 'As passwords não coincidem.' });
      return;
    }

    setLoading(true);
    try {
      // O utilizador já está autenticado pelo link de recuperação
      const { error } = await supabase.auth.updateUser({ password: password });
      
      if (error) throw error;

      setStatus({ type: 'success', msg: 'Sucesso! A tua password foi atualizada.' });
      
      // Manda para o ecrã inicial (index) após 3 segundos
      setTimeout(() => router.replace('/'), 3000);

    } catch (err: any) {
      setStatus({ type: 'error', msg: 'Erro ao atualizar. O link pode ter expirado.' });
    } 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}
        >
          <View style={styles.content}>
            <View style={styles.header}>
              <View style={styles.iconWrapper}>
                <View style={styles.iconCircle}>
                  <Ionicons name="lock-open-outline" size={38} color="#2390a6" />
                </View>
                <View style={styles.iconBadge} />
              </View>
              
              <Text style={styles.title}>Nova Palavra-passe</Text>
              <Text style={styles.subtitle}>
                Cria uma nova senha segura para acederes à tua conta.
              </Text>
            </View>

            {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' }]}>Nova Password</Text>
                <TextInput
                  style={[styles.input, isFocused && styles.inputFocused]}
                  placeholder="Mínimo 6 caracteres"
                  placeholderTextColor="#94A3B8"
                  value={password}
                  onChangeText={setPassword}
                  onFocus={() => setIsFocused(true)}
                  onBlur={() => setIsFocused(false)}
                  secureTextEntry
                  editable={!loading}
                />
              </View>

              <View style={styles.inputWrapper}>
                <Text style={styles.label}>Confirmar Password</Text>
                <TextInput
                  style={styles.input}
                  placeholder="Repita a password"
                  placeholderTextColor="#94A3B8"
                  value={confirmPassword}
                  onChangeText={setConfirmPassword}
                  secureTextEntry
                  editable={!loading}
                />
              </View>

              <TouchableOpacity
                activeOpacity={0.8}
                style={[styles.button, loading && styles.buttonDisabled]}
                onPress={handleUpdatePassword}
                disabled={loading}
              >
                {loading ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <Text style={styles.buttonText}>Atualizar Password</Text>
                )}
              </TouchableOpacity>
            </View>
          </View>

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

const styles = StyleSheet.create({
  mainContainer: { flex: 1, backgroundColor: '#FFFFFF' },
  scrollContainer: { 
    flexGrow: 1, 
    paddingHorizontal: 28,
    paddingTop: 80,
    paddingBottom: 40,
  },
  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,
  },
  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',
    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' },
});