import { useAuth } from "@/hook/use-auth";
import { useTranslation } from "react-i18next";
import { ConfirmationResult } from "@firebase/auth";
import { useCountDown } from "@/hook/use-countdown";
import { error, success } from "@/components/alert";
import React, { useEffect, useState } from "react";
import OTPInput from "react-otp-input";
import clsx from "clsx";
import { Button } from "@/components/button";
import { authService } from "@/services/auth";
import { setCookie } from "cookies-next";
import { userService } from "@/services/user";
import { useFcmToken } from "@/hook/use-fcm-token";
import useUserStore from "@/global-store/user";
import { useSyncServer } from "@/hook/use-sync-server";
import { useSettings } from "@/hook/use-settings";
import { isFirebaseConfigured } from "@/lib/firebase";

interface OtpConfirmationProps {
  credential?: string;
  confirmationResult?: ConfirmationResult | { confirm?: (otp: string) => Promise<any>; verifyId?: string };
  onConfirmationResultChange: (value: any) => void;
  onVerifySuccess: (meta?: { verifyId?: string; verifyCode?: string; phone?: string }) => void;
}

const OtpConfirmation = ({
  confirmationResult,
  credential,
  onConfirmationResultChange,
  onVerifySuccess,
}: OtpConfirmationProps) => {
  const { t } = useTranslation();
  const [otp, setOtp] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { settings } = useSettings();
  const waitTime = settings?.otp_expire_time ? Number(settings.otp_expire_time) * 60 : 60;
  const { counter: time, start: timerStart, reset: timerReset } = useCountDown(waitTime);
  const { phoneNumberSignIn } = useAuth();
  const { fcmToken } = useFcmToken();
  const localSignIn = useUserStore((state) => state.signIn);
  const { handleSync } = useSyncServer();

  const handleVerify = async () => {
    setIsSubmitting(true);
    const code = otp.replace(/\D/g, "");

    try {
      if (!isFirebaseConfigured) {
        const verifyId =
          String((confirmationResult as any)?.verifyId || "") ||
          sessionStorage.getItem("sms_verify_id") ||
          "";
        const phone =
          (credential || "").replace(/\D/g, "") ||
          sessionStorage.getItem("sms_verify_phone") ||
          "";

        if (!verifyId) {
          error(t("verify.error"));
          return;
        }

        await authService.checkOtp({
          verifyId,
          verifyCode: code,
          phone,
          type: "ippanel",
        });

        sessionStorage.setItem("sms_verify_id", verifyId);
        sessionStorage.setItem("sms_verify_code", code);
        sessionStorage.setItem("sms_verify_phone", phone);

        onVerifySuccess({ verifyId, verifyCode: code, phone });
        return;
      }

      const firebaseRes = await confirmationResult?.confirm?.(code);
      const token = await firebaseRes?.user.getIdToken();
      const res = await authService.forgotPasswordPhone({
        phone: credential?.replace(/[^0-9]/g, ""),
        type: "firebase",
        id: token,
      });
      setCookie("token", `Bearer ${res.data.access_token}`);
      if (fcmToken) {
        userService.updateFirebaseToken({ firebase_token: fcmToken });
      }
      localSignIn(res.data.user);
      handleSync();
      onVerifySuccess();
    } catch (err: any) {
      error(err?.message || t("verify.error"));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleResendCode = () => {
    if (credential) {
      phoneNumberSignIn(credential, { mode: "forgot" })
        .then((callback) => {
          timerReset();
          timerStart();
          success(t("verify.send"));
          onConfirmationResultChange(callback);
        })
        .catch((err) => error(err?.message || t("sms.not.sent")));
    }
  };

  useEffect(() => {
    timerStart();
  }, []);

  return (
    <div className="flex flex-col gap-6  ">
      <h1 className="font-semibold text-[30px] mb-2 text-start">{t("verify.phone")}</h1>
      <p className="text-sm">
        {t("verify.text")} <i>{credential}</i>
      </p>
      <div dir="ltr" className="w-full">
        <OTPInput
          value={otp}
          onChange={setOtp}
          containerStyle={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            gap: "10px",
            direction: "ltr",
          }}
          numInputs={6}
          inputType="tel"
          shouldAutoFocus
          renderInput={({ className, ...otherProps }) => (
            <input
              dir="ltr"
              inputMode="numeric"
              autoComplete="one-time-code"
              className={clsx(
                "flex-1 focus-visible:border-primary px-1 text-lg text-center border-gray-inputBorder bg-transparent rounded-2xl border appearance-none focus:outline-none py-5 focus:ring-0",
                className
              )}
              {...otherProps}
            />
          )}
        />
      </div>
      <div className="flex items-center gap-2">
        {time > 0 && <p className="text-sm text-gray-field">{time}s</p>}
        <button
          onClick={handleResendCode}
          className={clsx(
            "outline-none focus-ring max-w-max text-sm",
            time > 0 && "text-gray-field"
          )}
        >
          {t("resend")}
        </button>
      </div>
      <Button loading={isSubmitting} onClick={handleVerify} fullWidth disabled={otp.length < 6}>
        {t("verify")}
      </Button>
    </div>
  );
};

export default OtpConfirmation;
