import { useState } from "react";
import {
  Text,
  View,
  TouchableOpacity,
  TextInput,
  ScrollView,
  Alert,
  ActivityIndicator,
} from "react-native";
import { useRouter } from "expo-router";
import * as Haptics from "expo-haptics";
import { Platform } from "react-native";

import { ScreenContainer } from "@/components/screen-container";
import { IconSymbol } from "@/components/ui/icon-symbol";
import { useColors } from "@/hooks/use-colors";
import { useAppAuth } from "@/lib/auth-context";
import { trpc } from "@/lib/trpc";

export default function ChangePasswordScreen() {
  const router = useRouter();
  const colors = useColors();
  const { user } = useAppAuth();

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const changePasswordMutation = trpc.appAuth.changePassword.useMutation();

  async function handleChangePassword() {
    if (!currentPassword.trim()) {
      Alert.alert("Atenção", "Digite sua senha atual.");
      return;
    }
    if (!newPassword.trim()) {
      Alert.alert("Atenção", "Digite a nova senha.");
      return;
    }
    if (newPassword.length < 4) {
      Alert.alert("Atenção", "A nova senha deve ter pelo menos 4 caracteres.");
      return;
    }
    if (newPassword !== confirmPassword) {
      Alert.alert("Atenção", "As senhas não coincidem.");
      return;
    }

    if (Platform.OS !== "web") {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
    }

    setIsSubmitting(true);
    try {
      await changePasswordMutation.mutateAsync({
        userId: user!.id,
        currentPassword: currentPassword,
        newPassword: newPassword,
      });

      if (Platform.OS !== "web") {
        Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      }

      Alert.alert("Sucesso", "Senha alterada com sucesso!", [
        { text: "OK", onPress: () => router.back() },
      ]);
    } catch (error: any) {
      Alert.alert("Erro", error.message || "Não foi possível alterar a senha.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <ScreenContainer edges={["top", "left", "right", "bottom"]} className="p-4">
      <ScrollView showsVerticalScrollIndicator={false} className="flex-1">
        {/* Header */}
        <View className="flex-row items-center mb-6">
          <TouchableOpacity onPress={() => router.back()} className="mr-4">
            <IconSymbol name="arrow-back" size={24} color={colors.foreground} />
          </TouchableOpacity>
          <Text className="text-2xl font-bold text-foreground">Alterar Senha</Text>
        </View>

        {/* Ícone */}
        <View className="items-center mb-6">
          <View 
            className="w-20 h-20 rounded-full items-center justify-center"
            style={{ backgroundColor: colors.primary + '20' }}
          >
            <IconSymbol name="lock" size={40} color={colors.primary} />
          </View>
        </View>

        {/* Formulário */}
        <View className="gap-4">
          {/* Senha Atual */}
          <View>
            <Text className="text-foreground font-medium mb-2">Senha Atual</Text>
            <TextInput
              value={currentPassword}
              onChangeText={setCurrentPassword}
              placeholder="Digite sua senha atual"
              placeholderTextColor={colors.muted}
              secureTextEntry
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </View>

          {/* Nova Senha */}
          <View>
            <Text className="text-foreground font-medium mb-2">Nova Senha</Text>
            <TextInput
              value={newPassword}
              onChangeText={setNewPassword}
              placeholder="Digite a nova senha"
              placeholderTextColor={colors.muted}
              secureTextEntry
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
            <Text className="text-muted text-xs mt-1">Mínimo de 4 caracteres</Text>
          </View>

          {/* Confirmar Nova Senha */}
          <View>
            <Text className="text-foreground font-medium mb-2">Confirmar Nova Senha</Text>
            <TextInput
              value={confirmPassword}
              onChangeText={setConfirmPassword}
              placeholder="Digite novamente a nova senha"
              placeholderTextColor={colors.muted}
              secureTextEntry
              returnKeyType="done"
              onSubmitEditing={handleChangePassword}
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </View>
        </View>

        {/* Botão Alterar */}
        <TouchableOpacity
          onPress={handleChangePassword}
          disabled={isSubmitting}
          activeOpacity={0.8}
          className="bg-primary rounded-2xl p-5 mt-6"
          style={{ opacity: isSubmitting ? 0.7 : 1 }}
        >
          {isSubmitting ? (
            <ActivityIndicator color="#FFFFFF" />
          ) : (
            <Text className="text-white text-lg font-bold text-center">ALTERAR SENHA</Text>
          )}
        </TouchableOpacity>
      </ScrollView>
    </ScreenContainer>
  );
}
