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 { User } from "@/types/user";
import { emailOrPhone } from "@/utils/helper";
import { router, useLocalSearchParams } from "expo-router";
import { EnvelopeIcon, DeviceMobileIcon } from "phosphor-react-native";
import { useMemo, useState } from "react";
import { View, Text } from "react-native";

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

  const isEmail = useMemo(() => !!email, [email]);
  const { verifyOTP, redirect, verifyLoading } = 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;
    }

    verifyOTP(
      {
        ...emailOrPhone(email ?? phone ?? "", isEmail),
        otp: otpInputHandler.otp,
      },
      {
        onSuccess: async (response) => {
          setOtpInputHandler((prev) => ({
            ...prev,
            isReset: true,
            isComplete: false,
            isInvalid: false,
          }));

          const updatedUser: User = await getUser();

          const redirectURL = await redirect(updatedUser);
          router.push(redirectURL as any);
        },
        onError: (error) => {
          setBackendError(
            error instanceof Error ? error.message : String(error),
          );
          setOtpInputHandler((prev) => ({
            ...prev,
            isReset: true,
            isComplete: false,
            isInvalid: true,
          }));
        },
      },
    );
  };

  return (
    <AuthLayout>
      <View className="pb-10">
        <View className="py-2">
          <BackButtonTitle
            title={isEmail ? "Verify Email" : "Verify Phone"}
          />
        </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" }}
          >
            {isEmail ? (
              <EnvelopeIcon size={32} color={primary.base} weight="duotone" />
            ) : (
              <DeviceMobileIcon size={32} color={primary.base} weight="duotone" />
            )}
          </View>
          <Text className="text-3xl font-manrope-extrabold text-slate-900 pt-5">
            Enter Verification Code
          </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 {isEmail ? "email" : "phone"} to verify your account.
          </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={verifyLoading}
            backendError={backendError}
          />
        </View>
      </View>
    </AuthLayout>
  );
}

