import { useTranslation } from "react-i18next";
import { ConfirmationResult } from "@firebase/auth";
import { error } from "@/components/alert";
import React, { useState } from "react";
import { SignUpViews } from "@/components/auth/types";
import OTPInput from "react-otp-input";
import clsx from "clsx";
import { Button } from "@/components/button";
import { isFirebaseConfigured } from "@/lib/firebase";
import { authService } from "@/services/auth";

interface OtpConfirmationProps {
  credential?: string;
  confirmationResult?: ConfirmationResult | { confirm: (otp: string) => Promise<any>; verifyId?: string };
  onSuccess: (value: string, meta?: { verifyId?: string; verifyCode?: string }) => void;
  onChangeView: (view: SignUpViews) => void;
}

const OtpConfirmation = ({
  confirmationResult,
  credential,
  onSuccess,
  onChangeView,
}: OtpConfirmationProps) => {
  const { t } = useTranslation();
  const [otp, setOtp] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

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

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

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

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

        onSuccess(code, { verifyId, verifyCode: code });
        onChangeView("COMPLETE");
        return;
      }

      const firebaseRes = await confirmationResult?.confirm(code);
      const idToken = await firebaseRes?.user.getIdToken();
      onSuccess(idToken as string);
      onChangeView("COMPLETE");
    } catch (err: any) {
      error(err?.message || t("verify.error"));
    } finally {
      setIsSubmitting(false);
    }
  };

  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>
      <Button loading={isSubmitting} onClick={handleVerify} fullWidth disabled={otp.length < 6}>
        {t("verify")}
      </Button>
    </div>
  );
};

export default OtpConfirmation;
