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 { useColors } from "@/hooks/use-colors";
import { useAppAuth } from "@/lib/auth-context";
import { trpc } from "@/lib/trpc";

export default function LoginScreen() {
  const router = useRouter();
  const colors = useColors();
  const { login } = useAppAuth();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const loginMutation = trpc.appAuth.login.useMutation();

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

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

    setIsSubmitting(true);
    try {
      const result = await loginMutation.mutateAsync({
        email: email.trim().toLowerCase(),
        password: password,
      });

      if (result.success && result.user) {
        await login(result.user);

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

        router.replace("/(tabs)");
      }
    } catch (error: any) {
      Alert.alert("Erro", error.message || "E-mail ou senha incorretos.");
    } finally {
      setIsSubmitting(false);
    }
  }

  function handleGoToRegister() {
    router.push("/register");
  }

  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">
          <Text className="text-3xl font-bold text-foreground">Grupo Samam</Text>
          <Text className="text-muted text-base mt-2">Sistema de Chamados de Manutenção</Text>
        </View>

        {/* Formulário */}
        <View className="gap-4">
          {/* E-mail */}
          <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"
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </View>

          {/* Senha */}
          <View>
            <Text className="text-foreground font-medium mb-2">Senha</Text>
            <TextInput
              value={password}
              onChangeText={setPassword}
              placeholder="Digite sua senha"
              placeholderTextColor={colors.muted}
              secureTextEntry
              returnKeyType="done"
              onSubmitEditing={handleLogin}
              className="bg-surface border border-border rounded-xl p-4 text-foreground text-base"
              style={{ color: colors.foreground }}
            />
          </View>
        </View>

        {/* Botão Entrar */}
        <TouchableOpacity
          onPress={handleLogin}
          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">ENTRAR</Text>
          )}
        </TouchableOpacity>

        {/* Esqueceu a senha */}
        <TouchableOpacity 
          onPress={() => router.push("/reset-password" as any)} 
          activeOpacity={0.7} 
          className="mt-4"
        >
          <Text className="text-center text-primary font-medium">Esqueceu a senha?</Text>
        </TouchableOpacity>

        {/* Link para Cadastro */}
        <TouchableOpacity onPress={handleGoToRegister} activeOpacity={0.7} className="mt-4">
          <Text className="text-center text-muted">
            Não tem uma conta?{" "}
            <Text className="text-primary font-semibold">Cadastre-se</Text>
          </Text>
        </TouchableOpacity>
      </ScrollView>
    </ScreenContainer>
  );
}
