/** @format */

import AuthLayout from "@/components/auth/auth-layout";
import InputGroup from "@/components/auth/InputGroup";
import SocialLogin from "@/components/auth/SocialLogin";
import Button from "@/components/ui/Button";
import { storage } from "@/configs/storage";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useAuthHandler } from "@/hooks/useAuthHandler";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { AuthStore } from "@/stores/auth";
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { HandWavingIcon } from "phosphor-react-native";
import { Controller, useForm } from "react-hook-form";
import { Keyboard, Pressable, Text, View } from "react-native";

interface LoginFormData {
    username: string;
    password: string;
    remember_me?: boolean;
    captcha_token?: string | null;
}

export default function SignIn() {
    const { primary } = useColor();
    const { login } = useAuthStore((state: AuthStore) => state);
    const {
        control,
        formState: { errors: formErrors },
        handleSubmit,
    } = useForm<LoginFormData>({
        defaultValues: {
            remember_me: false,
        },
    });

    const { redirect, setOtpBreakTimer, sendOTP } = useAuthHandler();

    const {
        mutate,
        isLoading,
        backendErrors: errors,
    } = useQueryMutation({
        isPublic: true,
        url: "/login",
    });

    const submitForm = (data: LoginFormData) => {
        Keyboard.dismiss();
        mutate(
            { ...data, captcha_token: "" },
            {
                onSuccess: async (response: any) => {
                    const data = response?.data;

                    if (!data?.user) {
                        return;
                    }

                    // Only login if token is present (2FA enabled means no token returned yet)
                    if (data?.token) {
                        await login(data.token, data.user);
                    }

                    if (data?.user?.is_2fa_enabled) {
                        // Set OTP timer
                        setOtpBreakTimer(data?.user?.email);

                        // Send OTP to user's email
                        sendOTP(
                            { type: "email", email: data?.user?.email },
                            {
                                onSuccess: () => {
                                    router.push(`/(auth)/verify-2fa?email=${encodeURIComponent(data?.user?.email)}` as any);
                                },
                                onError: () => {
                                    router.push(`/(auth)/verify-2fa?email=${encodeURIComponent(data?.user?.email)}` as any);
                                },
                            },
                        );
                        return;
                    }

                    const signInCount = storage.getString("sign_in_count");
                    if (data?.user?.phone_verified_at && signInCount === "2") {
                        storage.remove("sign_in_count");
                    }

                    // 2FA disabled — determine where to redirect
                    const redirectURL = await redirect(data?.user);

                    // Use setTimeout to ensure Keyboard dismissal and any Reanimated unmounts
                    // are fully processed on Android before we replace the router stack.
                    // This avoids the `addViewAt: failed to insert view` crash.
                    setTimeout(() => {
                        const finalURL = redirectURL === "/(tabs)" ? "/" : (redirectURL as any);
                        router.replace(finalURL);
                    }, 100);
                },
                onError: (err) => {
                    console.log(err, "Error");
                },
            },
        );
    };

    const onSubmit = handleSubmit((data) => {
        if (data) {
            submitForm(data);
        }
    });

    return (
        <AuthLayout>
            <View className="pb-10">
                <View className="py-2 ">
                    <Text className="text-slate-500  items-center justify-center pt-2 text-xl text-center font-manrope-bold">Sign In</Text>
                </View>

                <View className="mt-8 mb-6 p-6 rounded-3xl" style={{ backgroundColor: primary[5] }}>
                    <View className="size-14 rounded-2xl justify-center items-center shadow-sm" style={{ backgroundColor: "white" }}>
                        <HandWavingIcon size={32} color={primary.base} weight="duotone" />
                    </View>
                    <Text className="text-3xl font-manrope-extrabold text-slate-900 pt-5">Welcome Back</Text>
                    <Text className="text-slate-500 w-[95%] pt-2 text-lg font-manrope-medium">Sign in to continue managing your real estate investments.</Text>
                </View>

                <View className="py-2 gap-y-5">
                    <InputGroup control={control} label="Email Address" name="username" error={formErrors.username} backendError={errors?.username} keyboardType="email-address" />
                    <InputGroup control={control} label="Password" name="password" error={formErrors.password} backendError={errors?.password} secureTextEntry={true} />

                    <View className="flex-row justify-between items-center mb-2">
                        <Controller
                            control={control}
                            name="remember_me"
                            defaultValue={false}
                            render={({ field: { onChange, value = false } }) => (
                                <Pressable className="flex-row items-center gap-x-2.5" onPress={() => onChange(!value)}>
                                    <View
                                        className={`size-5 rounded-md border items-center justify-center shadow-sm transition-all`}
                                        style={{
                                            backgroundColor: value ? primary.base : "white",
                                            borderColor: value ? primary.base : "#cbd5e1",
                                        }}
                                    >
                                        {value && <Ionicons name="checkmark" size={14} color="white" />}
                                    </View>
                                    <Text className="text-slate-600 font-manrope-semibold text-base">Remember me</Text>
                                </Pressable>
                            )}
                        />

                        <Pressable onPress={() => router.push("/forgot-password")}>
                            <Text className="text-base font-manrope-bold" style={{ color: primary.base }}>
                                Forgot Password?
                            </Text>
                        </Pressable>
                    </View>

                    <Button onPress={onSubmit} isLoading={isLoading} text="Sign In" className="mt-2" />
                </View>

                <View className="flex-row justify-center items-center my-10 gap-x-4">
                    <View className="h-px bg-slate-100 flex-1"></View>
                    <Text className="text-slate-400 font-manrope-bold text-xs uppercase tracking-widest">Or Sign In With</Text>
                    <View className="h-px bg-slate-100 flex-1"></View>
                </View>

                <SocialLogin />

                <Pressable onPress={() => router.push("/(auth)/sign-up")} className="mt-8 flex-row justify-center items-center gap-x-1">
                    <Text className="text-slate-500 font-manrope-medium text-base">Don&apos;t have an account?</Text>
                    <Text className="font-manrope-bold text-base" style={{ color: primary.base }}>
                        Sign Up
                    </Text>
                </Pressable>
            </View>
        </AuthLayout>
    );
}
