import React, { useState } from 'react';
import { View, Text, StyleSheet, TextInput, ScrollView, ActivityIndicator, Alert, useColorScheme } from 'react-native';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { useAuthStore } from '@/store/authStore';
import { Ionicons } from '@expo/vector-icons';
import Animated, { FadeInDown } from 'react-native-reanimated';
import GlassCard from '@/components/common/GlassCard';
import AnimatedButton from '@/components/common/AnimatedButton';
import { useRouter } from 'expo-router';

export default function SecurityScreen() {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const { user_id, logout } = useAuthStore();
  const router = useRouter();

  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState(false);

  const handleChangePassword = async () => {
    if (!currentPassword || !newPassword || !confirmPassword) {
      Alert.alert('Aviso', 'Por favor, preencha todos os campos.');
      return;
    }
    if (newPassword !== confirmPassword) {
      Alert.alert('Aviso', 'A nova senha e a confirmação não coincidem.');
      return;
    }

    setSaving(true);
    try {
      const response = await api.post('/change-password', {
        auth_id: user_id,
        current_password: currentPassword,
        new_password: newPassword,
        confirm_password: confirmPassword,
        is_mobile: 'yes'
      });

      if (response.data?.code === 200 || response.data?.status === true) {
        Alert.alert('Sucesso', 'Senha alterada com sucesso!');
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
      } else {
        const errorMsg = response.data?.message || 'Falha ao alterar senha.';
        Alert.alert('Erro', errorMsg);
      }
    } catch (error: any) {
      console.error('Error changing password:', error);
      const serverMsg = error.response?.data?.message || error.response?.data?.errors?.[0] || 'Ocorreu um erro ao comunicar com o servidor.';
      Alert.alert('Erro', serverMsg);
    } finally {
      setSaving(false);
    }
  };

  const handleDeleteAccount = () => {
    Alert.alert(
      'Atenção',
      'Tem certeza que deseja solicitar a eliminação da sua conta? Esta ação não pode ser desfeita.',
      [
        { text: 'Cancelar', style: 'cancel' },
        { 
          text: 'Eliminar', 
          style: 'destructive',
          onPress: async () => {
            setDeleting(true);
            try {
              const res = await api.post('/delete-account', { id: user_id });
              if (res.data?.status || res.data?.code === 200) {
                Alert.alert('Conta Eliminada', 'A sua conta foi marcada para eliminação.');
                await logout();
                router.replace('/login');
              } else {
                Alert.alert('Erro', res.data?.message || 'Falha ao eliminar conta.');
              }
            } catch (error) {
              console.error('Delete account error', error);
              Alert.alert('Erro', 'Ocorreu um erro.');
            } finally {
              setDeleting(false);
            }
          }
        }
      ]
    );
  };

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <ScrollView contentContainerStyle={styles.content} showsVerticalScrollIndicator={false}>
        <Animated.View entering={FadeInDown.duration(400).delay(100)}>
          <GlassCard style={styles.card}>
            <View style={styles.headerRow}>
               <View style={[styles.iconCircle, { backgroundColor: `${theme.primary}15` }]}>
                 <Ionicons name="lock-closed" size={24} color={theme.primary} />
               </View>
               <View style={styles.headerText}>
                 <Text style={[styles.title, { color: theme.text }]}>Alterar Senha</Text>
                 <Text style={[styles.subtitle, { color: theme.textMuted }]}>Proteja a sua conta com uma senha forte</Text>
               </View>
            </View>

            <View style={styles.inputGroup}>
              <Text style={[styles.label, { color: theme.textMuted }]}>Senha Atual</Text>
              <TextInput 
                style={[styles.input, { color: theme.text, borderColor: theme.border, backgroundColor: `${theme.text}05` }]}
                value={currentPassword}
                onChangeText={setCurrentPassword}
                secureTextEntry
                placeholderTextColor={theme.textMuted}
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={[styles.label, { color: theme.textMuted }]}>Nova Senha</Text>
              <TextInput 
                style={[styles.input, { color: theme.text, borderColor: theme.border, backgroundColor: `${theme.text}05` }]}
                value={newPassword}
                onChangeText={setNewPassword}
                secureTextEntry
                placeholderTextColor={theme.textMuted}
              />
            </View>

            <View style={styles.inputGroup}>
              <Text style={[styles.label, { color: theme.textMuted }]}>Confirmar Nova Senha</Text>
              <TextInput 
                style={[styles.input, { color: theme.text, borderColor: theme.border, backgroundColor: `${theme.text}05` }]}
                value={confirmPassword}
                onChangeText={setConfirmPassword}
                secureTextEntry
                placeholderTextColor={theme.textMuted}
              />
            </View>
            
            <AnimatedButton 
              title={saving ? "A Atualizar..." : "Atualizar Senha"} 
              onPress={handleChangePassword} 
              disabled={saving}
              style={{ marginTop: 10 }}
            />
          </GlassCard>
        </Animated.View>

        <Animated.View entering={FadeInDown.duration(400).delay(200)}>
          <GlassCard style={[styles.card, { borderColor: `${theme.error}30`, borderWidth: 1, marginTop: 24 }]}>
             <View style={styles.headerRow}>
               <View style={[styles.iconCircle, { backgroundColor: `${theme.error}15` }]}>
                 <Ionicons name="warning" size={24} color={theme.error} />
               </View>
               <View style={styles.headerText}>
                 <Text style={[styles.title, { color: theme.error }]}>Zona de Perigo</Text>
                 <Text style={[styles.subtitle, { color: theme.textMuted }]}>Ações irreversíveis para a sua conta</Text>
               </View>
            </View>
            
            <Text style={{ color: theme.textMuted, fontSize: 13, marginBottom: 20, lineHeight: 18 }}>
              Ao solicitar a eliminação da sua conta, todos os seus dados pessoais, histórico de serviços e configurações serão removidos permanentemente.
            </Text>

            <AnimatedButton 
              title={deleting ? "A Processar..." : "Eliminar Minha Conta"} 
              onPress={handleDeleteAccount} 
              variant="outline"
              disabled={deleting}
              colors={[theme.error, theme.error]}
              textStyle={{ color: theme.error }}
            />
          </GlassCard>
        </Animated.View>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  content: { padding: 20, paddingBottom: 100 },
  card: {
    padding: 20,
    borderRadius: 20,
  },
  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 24,
  },
  iconCircle: {
    width: 48,
    height: 48,
    borderRadius: 24,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 16,
  },
  headerText: { flex: 1 },
  title: { fontSize: 18, fontWeight: '700', letterSpacing: -0.5 },
  subtitle: { fontSize: 13, marginTop: 2 },
  inputGroup: { marginBottom: 16 },
  label: { fontSize: 13, fontWeight: '600', marginBottom: 8, marginLeft: 4 },
  input: { 
    height: 54, 
    borderWidth: 1, 
    borderRadius: 12, 
    paddingHorizontal: 16,
    fontSize: 15,
  }
});
