import AuthLayout from "@/components/auth/auth-layout";
import OtpForm from "@/components/auth/OtpForm";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { emailOrPhone } from "@/utils/helper";
import { router, useLocalSearchParams } from "expo-router";
import { ChatCenteredText } from "phosphor-react-native";
import { useMemo, useState } from "react";
import { Text, View } from "react-native";
import BackButtonTitle from "@/components/ui/BackButtonTitle";

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

  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 isEmail = useMemo(() => !!email, [email]);

  const { mutate: verifyOTP, isLoading: verifyLoading } = useQueryMutation({
    isPublic: true,
    url: "/send-otp",
  });

  const { mutate: verifyEmailPhoneOtp, isLoading: isVerifying } =
    useQueryMutation({
      url: "/verify-email-or-phone",
      isPublic: true,
    });

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

    verifyEmailPhoneOtp(
      {
        ...emailOrPhone(email ?? phone ?? "", isEmail),
        otp: otpInputHandler.otp,
        only_otp_check: 1,
      },
      {
        onSuccess: async (response) => {
          //   toast.success("OTP verified successfully");
          setOtpInputHandler((prev) => ({
            ...prev,
            isReset: true,
            isComplete: false,
            isInvalid: false,
          }));
          router.push(`/change-password?otp=${otpInputHandler.otp}&email=${email}`);
        },
        onError: (error) => {
          console.log(error, "otp 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="Verify Account" 
            onPress={() => router.push("/(auth)/sign-in")} 
          />
        </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" }}
          >
            <ChatCenteredText size={32} color={primary.base} weight="duotone" />
          </View>
          <Text className="text-3xl font-manrope-extrabold text-slate-900 pt-5">
            Verify OTP
          </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 ? "email" : "phone"} to secure 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>
  );
}
