import AuthLayout from "@/components/auth/auth-layout";
import OtpForm from "@/components/auth/OtpForm";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import { useAuthHandler } from "@/hooks/useAuthHandler";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { showToast } from "@/utils/toast";
import { router, useLocalSearchParams } from "expo-router";
import { ShieldCheckIcon } from "phosphor-react-native";
import { useState } from "react";
import { Text, View, Keyboard } from "react-native";

export default function Verify2FA() {
  const [backendError, setBackendError] = useState<null | string>(null);
  const { primary } = useColor();
  const { appInfo, login } = useAuthStore((state: any) => state);
  const { email } = useLocalSearchParams<{ email?: string }>();

  const { signInWith2fa, signInWith2faLoading, redirect } = useAuthHandler();

  const [otp, setOtp] = useState<string[]>(Array(6).fill(""));
  const [otpInputHandler, setOtpInputHandler] = useState<{
    otp: string;
    isReset: boolean;
    isComplete: boolean;
    isInvalid: boolean;
  }>({
    otp: "",
    isReset: false,
    isComplete: false,
    isInvalid: false,
  });

  const handleVerify = () => {
    if (!otpInputHandler.otp.length) {
      setOtpInputHandler((prev) => ({
        ...prev,
        isInvalid: true,
        isComplete: false,
        isReset: false,
      }));
      return;
    }

    signInWith2fa(
      {
        email: email,
        otp: otpInputHandler.otp,
      },
      {
        onSuccess: async (response: any) => {
          setOtpInputHandler((prev) => ({
            ...prev,
            isReset: true,
            isComplete: false,
            isInvalid: false,
          }));

          const data = response?.data;

          if (data?.token && data?.user) {
            await login(data.token, data.user);

            showToast({
              type: "success",
              text: "Login successful",
            });

            Keyboard.dismiss();
            
            const redirectURL = await redirect(data.user);
            // Use "/" for tabs destination to avoid Android addViewAt crash
            const finalURL = redirectURL === "/(tabs)" ? "/" : (redirectURL as any);
            
            setTimeout(() => {
              router.replace(finalURL);
            }, 100);
          } else {
            Keyboard.dismiss();
            showToast({
              type: "success",
              text: "Verified successfully",
            });
            setTimeout(() => {
              router.replace("/");
            }, 100);
          }
        },
        onError: (error: any) => {
          const message =
            error?.response?.data?.message ||
            (error instanceof Error ? error.message : String(error));
          setBackendError(message);
          setOtpInputHandler((prev) => ({
            ...prev,
            isReset: true,
            isComplete: false,
            isInvalid: true,
          }));
        },
      },
    );
  };

  return (
    <AuthLayout>
      <View className="pb-10">
        <View className="py-2">
          <BackButtonTitle title="Two-Factor Authentication" />
        </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" }}>
            <ShieldCheckIcon size={32} color={primary.base} weight="duotone" />
          </View>
          <Text className="text-3xl font-manrope-extrabold text-slate-900 pt-5">Security Verification</Text>
          <Text className="text-slate-500 w-[95%] pt-2 text-lg font-manrope-medium leading-6">
            Enter the 6-digit code sent to your email to complete sign in.
          </Text>
        </View>

        <View className="py-4">
          <OtpForm
            length={6}
            onComplete={() => {}}
            otp={otp}
            setOtp={setOtp}
            time={Number(appInfo?.application_info?.otp?.expire_time) || 45}
            handleVerify={handleVerify}
            otpInputHandler={otpInputHandler}
            setOtpInputHandler={setOtpInputHandler}
            otpSendLoading={signInWith2faLoading}
            backendError={backendError}
          />
        </View>
      </View>
    </AuthLayout>
  );
}
