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 { trpc } from "@/lib/trpc";

export default function ResetPasswordScreen() {
  const router = useRouter();
  const colors = useColors();

  const [step, setStep] = useState<"email" | "password">("email");
  const [email, setEmail] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const checkEmailQuery = trpc.appAuth.checkEmail.useQuery(
    { email: email.trim().toLowerCase() },
    { enabled: false }
  );
  const resetPasswordMutation = trpc.appAuth.resetPassword.useMutation();

  async function handleCheckEmail() {
    if (!email.trim()) {
      Alert.alert("Atenção", "Digite seu e-mail.");
      return;
    }

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

    setIsSubmitting(true);
    try {
      const result = await checkEmailQuery.refetch();
      
      if (result.data?.exists) {
        setStep("password");
      } else {
        Alert.alert("E-mail não encontrado", "Este e-mail não está cadastrado no sistema.");
      }
    } catch (error: any) {
      Alert.alert("Erro", "Não foi possível verificar o e-mail.");
    } finally {
      setIsSubmitting(false);
    }
  }

  async function handleResetPassword() {
    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 resetPasswordMutation.mutateAsync({
        email: email.trim().toLowerCase(),
        newPassword: newPassword,
      });

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

      Alert.alert("Sucesso", "Senha redefinida com sucesso! Faça login com a nova senha.", [
        { text: "OK", onPress: () => router.replace("/login") },
      ]);
    } catch (error: any) {
      Alert.alert("Erro", error.message || "Não foi possível redefinir a senha.");
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <ScreenContainer edges={["top", "left", "right", "bottom"]} className="p-4">
      <ScrollView
        showsVerticalScrollIndicator={false}
        className="flex-1"
        contentContainerStyle={{ flexGrow: 1, justifyContent: "center" }}
      >
        {/* Header */}
        <View className="items-center mb-8">
          <View 
            className="w-20 h-20 rounded-full items-center justify-center mb-4"
            style={{ backgroundColor: colors.primary + '20' }}
          >
            <IconSymbol name="lock" size={40} color={colors.primary} />
          </View>
          <Text className="text-3xl font-bold text-foreground">Recuperar Senha</Text>
          <Text className="text-muted text-base mt-2 text-center">
            {step === "email" 
              ? "Digite seu e-mail cadastrado" 
              : "Digite sua nova senha"}
          </Text>
        </View>

        {step === "email" ? (
          <>
            {/* Formulário de E-mail */}
            <View className="gap-4">
              <View>
                <Text className="text-foreground font-medium mb-2">E-mail</Text>
                <TextInput
                  value={email}
                  onChangeText={setEmail}
                  placeholder="Digite seu e-mail"
                  placeholderTextColor={colors.muted}
                  keyboardType="email-address"
                  autoCapitalize="none"
                  autoComplete="email"
                  returnKeyType="done"
                  onSubmitEditing={handleCheckEmail}
                  className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
                  style={{ color: colors.foreground }}
                />
              </View>
            </View>

            {/* Botão Continuar */}
            <TouchableOpacity
              onPress={handleCheckEmail}
              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">CONTINUAR</Text>
              )}
            </TouchableOpacity>
          </>
        ) : (
          <>
            {/* Formulário de Nova Senha */}
            <View className="gap-4">
              <View className="bg-surface border border-border rounded-xl p-4">
                <Text className="text-muted text-sm">E-mail</Text>
                <Text className="text-foreground font-medium">{email}</Text>
              </View>

              <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>

              <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={handleResetPassword}
                  className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
                  style={{ color: colors.foreground }}
                />
              </View>
            </View>

            {/* Botão Redefinir */}
            <TouchableOpacity
              onPress={handleResetPassword}
              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">REDEFINIR SENHA</Text>
              )}
            </TouchableOpacity>

            {/* Voltar */}
            <TouchableOpacity 
              onPress={() => setStep("email")} 
              activeOpacity={0.7} 
              className="mt-4"
            >
              <Text className="text-center text-muted">Voltar</Text>
            </TouchableOpacity>
          </>
        )}

        {/* Link para Login */}
        <TouchableOpacity 
          onPress={() => router.push("/login")} 
          activeOpacity={0.7} 
          className="mt-6"
        >
          <Text className="text-center text-muted">
            Lembrou a senha?{" "}
            <Text className="text-primary font-semibold">Fazer login</Text>
          </Text>
        </TouchableOpacity>
      </ScrollView>
    </ScreenContainer>
  );
}
