import { signIn, authClient } from "@/src/lib/auth-client";
import { apiRequest } from "@/src/lib/api-client";
import { useAuthStore, type Household } from "@/src/stores/auth.store";
import { useRouter } from "expo-router";
import { useState } from "react";
import * as AppleAuthentication from "expo-apple-authentication";
import {
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
  Pressable,
  Text,
  TextInput,
  View,
} from "react-native";
import { useTranslation } from "react-i18next";

export default function LoginScreen() {
  const router = useRouter();
  const { t } = useTranslation();
  const { setUser, setHouseholds, setActiveHousehold } = useAuthStore();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleEmailSignIn() {
    if (!email || !password) {
      setError(t('login.fillAllFields'));
      return;
    }
    setIsLoading(true);
    setError(null);
    try {
      const result = await signIn.email({ email, password });
      if (result.error) {
        const msg = result.error.message ?? "";
        if (msg.toLowerCase().includes("email") && msg.toLowerCase().includes("verif")) {
          router.push({ pathname: "/(auth)/verify-email", params: { email } });
          return;
        }
        setError(msg || t('login.signInError'));
        return;
      }
      if (result.data?.user) setUser(result.data.user);
      try {
        const { households } = await apiRequest<{ households: Household[] }>("/api/households");
        setHouseholds(households);
        if (households.length > 0) setActiveHousehold(households[0].id);
      } catch {
        // households will be loaded on next app start
      }
      router.replace("/(app)/haushalt");
    } catch {
      setError(t('login.signInError'));
    } finally {
      setIsLoading(false);
    }
  }

  async function handleAppleSignIn() {
    try {
      const credential = await AppleAuthentication.signInAsync({
        requestedScopes: [
          AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
          AppleAuthentication.AppleAuthenticationScope.EMAIL,
        ],
      });
      if (!credential.identityToken) return;
      const result = await authClient.signIn.social({
        provider: "apple",
        idToken: { token: credential.identityToken },
      });
      if (result.error) {
        setError(result.error.message ?? t('common.error'));
        return;
      }
      // session is handled by authClient interceptor
      router.replace("/(app)/haushalt");
    } catch (err: unknown) {
      if ((err as { code?: string }).code !== "ERR_CANCELED") {
        setError(t('login.appleSignInError'));
      }
    }
  }

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === "ios" ? "padding" : "height"}
      className="flex-1 bg-white"
    >
      <View className="flex-1 justify-center px-6">
        <Text className="mb-2 text-3xl font-bold text-gray-900">
          {t('login.welcome')}
        </Text>
        <Text className="mb-8 text-base text-gray-500">
          {t('login.subtitle')}
        </Text>

        {error && (
          <View className="mb-4 rounded-lg bg-red-50 p-3">
            <Text className="text-sm text-red-600">{error}</Text>
          </View>
        )}

        {Platform.OS === "ios" && (
          <>
            <AppleAuthentication.AppleAuthenticationButton
              buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
              buttonStyle={AppleAuthentication.AppleAuthenticationButtonStyle.BLACK}
              cornerRadius={12}
              style={{ width: "100%", height: 50 }}
              onPress={handleAppleSignIn}
            />
            <View className="flex-row items-center gap-3 my-4">
              <View className="flex-1 h-px bg-gray-200" />
              <Text className="text-xs text-gray-400">{t('common.or')}</Text>
              <View className="flex-1 h-px bg-gray-200" />
            </View>
          </>
        )}

        <View className="mb-4">
          <Text className="mb-1.5 text-sm font-medium text-gray-700">
            {t('login.emailLabel')}
          </Text>
          <TextInput
            className="rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-base text-gray-900"
            placeholder={t('login.emailPlaceholder')}
            value={email}
            onChangeText={setEmail}
            autoCapitalize="none"
            keyboardType="email-address"
            autoComplete="email"
          />
        </View>

        <View className="mb-6">
          <Text className="mb-1.5 text-sm font-medium text-gray-700">
            {t('login.passwordLabel')}
          </Text>
          <TextInput
            className="rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-base text-gray-900"
            placeholder={t('login.passwordPlaceholder')}
            value={password}
            onChangeText={setPassword}
            secureTextEntry
            autoComplete="password"
          />
        </View>

        <Pressable
          onPress={handleEmailSignIn}
          disabled={isLoading}
          className="mb-3 items-center rounded-xl bg-blue-600 py-4 active:opacity-80"
        >
          {isLoading ? (
            <ActivityIndicator color="white" />
          ) : (
            <Text className="text-base font-semibold text-white">{t('login.signIn')}</Text>
          )}
        </Pressable>

        <Pressable
          onPress={() => router.push("/(auth)/forgot-password")}
          className="mb-6 items-center py-2 active:opacity-60"
        >
          <Text className="text-sm text-blue-600">{t('login.forgotPassword')}</Text>
        </Pressable>

        <View className="flex-row justify-center">
          <Text className="text-sm text-gray-500">{t('login.noAccount')} </Text>
          <Pressable onPress={() => router.push("/(auth)/register")}>
            <Text className="text-sm font-semibold text-blue-600">
              {t('login.register')}
            </Text>
          </Pressable>
        </View>
      </View>
    </KeyboardAvoidingView>
  );
}
