import React, { useEffect, useState, Dispatch, SetStateAction } from "react";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import axios from "@/utils/axios-config";
import OtpInput from "react-otp-input";
import { useDispatch } from "react-redux";
import { ArrowRightOutlined } from "@ant-design/icons";
import { usePathname } from "next/navigation";
import { message, Button, Modal } from "antd";
import { GiConfirmed } from "react-icons/gi";
import { saveToken } from "@/utils/cookie-config";
import loginActions from "@/store/auth/actions";
import { registerFCMToken } from "@/utils/firebase";

type props = {
  phone: any;
  otpTimerStart: boolean;
  setPageParts?: Dispatch<SetStateAction<string>>;
  setOtp?: Dispatch<SetStateAction<string>>;
  setOtpTimerStart: Dispatch<SetStateAction<boolean>>;
};

export default function Otp(props: props) {
  const [otp, setOtp] = useState("");
  const [otpTimer, setOtpTimer] = useState(60);
  const [seconds, setSeconds] = useState(otpTimer % 60);
  const [minutes, setMinutes] = useState(Math.floor(otpTimer / 60));
  const [hideOtpTimer, setHideOtpTimer] = useState(false);
  const [showOtp, setShowOtp] = useState(false);
  const [loading, setLoading] = useState(false);
  const [successModalOpen, setSuccessModalOpen] = useState(false);
  const [language, setLanguage] = useState("");
  const [userData, setUserData] = useState({
    phone_number: "",
    iqama_number: "",
  });
  const dispatch = useDispatch();
  const t = useTranslations();
  const locale = useLocale();
  const pathname = usePathname();

  const otpChangeHandler = (e: any) => {
   // console.log("otp", e);
    setOtp(e);
  };

  useEffect(() => {
    // if (hideOtpTimer) {
    // let timer;
    if (props.otpTimerStart) {
      const timer = setInterval(() => {
        setOtpTimer((prevOtpTimer) => {
          // Use the previous state to ensure correct updates
          const newOtpTimer = prevOtpTimer - 1;
          if (newOtpTimer === -1) {
            props.setOtpTimerStart(false);
            clearInterval(timer);

            //setOtpTimer(60);
          } else {
            setSeconds(newOtpTimer % 60);
            setMinutes(Math.floor(newOtpTimer / 60));
          }
          return newOtpTimer;
        });
      }, 1000);
      //}
      // Clear the interval on component unmount or when hideOtpTimer changes
      return () => clearInterval(timer);
    }
  }, [props?.otpTimerStart]);
  ////verify otp
  const verifyOtp = async () => {
    if (!otp) {
     // message.error(t("please-enter-code"));
      return;
    }
    setLoading(true);
    try {
      console.log("pathname", pathname?.split("/")[1]);
      if (pathname?.split("/")[1] === "forget-password") {
        const response = await axios.post("auth/verify-code", {
          phone: props.phone,
          code: otp,
        });
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        props.setPageParts && props.setPageParts("new-pass");
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        props.setOtp && props.setOtp(otp);
      } else {
        const response = await axios.post("auth/verify", {
          phone: props.phone,
          code: otp,
        });

        //message.success(response?.data?.message);
        saveToken(response?.data?.token);
        dispatch(loginActions?.login(response?.data?.token));
        registerFCMToken(); // Register FCM token after successful verification
        setSuccessModalOpen(true);
      }
    } catch (err: any) {
      message.error(t("code-invalid"));
    } finally {
      setLoading(false);
    }
  };

  ///resend otp
  const sendCode = async () => {
    try {
      const response = await axios.post("auth/send-code", {
        phone: props.phone,
        usage: "verify",
      });

      props.setOtpTimerStart(true);
      setOtpTimer(60);
    } catch (err: any) {
      message.error(err?.data?.message);
    }
  };
  ///////////////////

  return (
    <>
      <div>
        <div className="page-container" style={{ flexDirection: "column" }}>
          <>
            <div className="flex flex-col items-center">
              <p className="py-6 text-[20px] md:text-[30px] font-semibold text-primary">
                {t("verification-code")}
              </p>
              <OtpInput
                //inputType="number"
                value={otp}
                onChange={otpChangeHandler}
                numInputs={4}
                renderSeparator={<span style={{ width: "8px" }}></span>}
                renderInput={(props) => <input {...props} />}
                // isInputNum={true}
                shouldAutoFocus={true}
                // className={styles.otpInput}
                containerStyle={{
                  justifyContent: "center",
                  // marginTop: "4em",
                  direction: "ltr",
                }}
                inputStyle={{
                  border: "1px solid #03B89E",
                  borderRadius: "8px",
                  // width: width > 400 ? "10%" : "100%",
                  width: "60px",
                  height: "60px",
                  fontSize: "16px",
                  color: "black",
                  fontWeight: "400",
                  caretColor: "blue",
                 
                 
                  //direction:"ltr !important",
                  margin: "0px 6px 0 6px",
                }}
              />
             {!otp&&<p className="text-custom-red pt-4">{t('please-enter-code')}</p>}
              <Button
                onClick={verifyOtp}
                //  htmlType="submit"
                loading={loading}
                className={`w-[200px] mx-auto mt-[50px] h-[50px] sm:h-[56px] !border-none !outline-none !text-white !bg-[#03B89E]  rounded-md text-[20px] sm:text-[24px] font-[600] flex items-center justify-center border  transition-colors duration-500 group`}
              >
                {t("verify")}
                <ArrowRightOutlined
                  className={`mx-[7px] bg-[#fff] text-[#03B89E] p-[4px] rounded-full text-[14px] transition-colors duration-300
                     rtl:rotate-180 `}
                />
              </Button>
              {otpTimer <= 0 ? (
                <p
                  className="text-custom-red cursor-pointer"
                  onClick={() => sendCode()}
                >
                  {t("resend-otp")}
                </p>
              ) : (
                <p
                  style={{
                    padding: "10px",
                    backgroundColor: "white",
                    border: "none",
                    borderRadius: "5px",
                    margin: "15px auto ",
                    color: otpTimer <= 10 ? "red" : "black",
                    marginBottom: "25px",
                  }}
                >
                  {`${String(minutes).padStart(2, "0")}:${String(
                    seconds
                  ).padStart(2, "0")}`}
                </p>
              )}
            </div>
          </>
        </div>
      </div>

      {/*****browse modal**** */}
      <Modal open={successModalOpen} closable={false} footer={null}>
        <div className="py-8 flex flex-col items-center">
          <GiConfirmed className="text-[40px] md:text-[100px] text-primary" />
          <p className="font-bold pt-8 pb-6 text-[20px]  md:text-[30px] text-primary">
            {t("verified-successfully")}
          </p>
          <Button
            className={`w-[200px] mx-auto h-[50px] sm:h-[56px] !border-none !outline-none !text-white !bg-[#03B89E]  rounded-md text-[20px] sm:text-[24px] font-[600] flex items-center justify-center border  transition-colors duration-500 group`}
          >
            <Link href={`/${locale}/`} locale={false}>
              {t("browse-now")}
              <ArrowRightOutlined
                className={`mx-[7px] bg-[#fff] text-[#03B89E] p-[4px] rounded-full text-[14px] transition-colors duration-300   
                  rtl:rotate-180
                `}
              />
            </Link>
          </Button>
        </div>
      </Modal>
    </>
  );
}
