import RetryLogin from "@/components/icons/RetryLogin";
import { changeNumToDefault } from "@/helper";
import { request } from "@/services/response";
import { Button } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import Altcha from "@/components/Altcha";

const time_resend_code = 120;

function Recode({ retryIcon, timer, setUuid, num, setTimer }) {
  const timerIntervalRef = useRef(null);
  const animIntervalRef = useRef(null);
  const [altcha, setAltcha] = useState("");
  const [altchaKey, setAltchaKey] = useState(0);

  useEffect(() => {
    return () => {
      if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
      if (animIntervalRef.current) clearInterval(animIntervalRef.current);
    };
  }, []);

  const handleTimer = () => {
    setTimer("loading");
    if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
    setTimeout(() => {
      setTimer(time_resend_code);
      let timePresent = time_resend_code;
      timerIntervalRef.current = setInterval(() => {
        timePresent--;
        setTimer(timePresent);
        if (!timePresent) {
          clearInterval(timerIntervalRef.current);
          timerIntervalRef.current = null;
        }
      }, 1000);
    }, 1000);
  };

  const rotateIcon = () => {
    if (!retryIcon.current) return;
    retryIcon.current.classList.add("retry-icon");
    setTimeout(() => {
      retryIcon.current?.classList.remove("retry-icon");
    }, 1000);
  };

  const handleReq = () => {
    rotateIcon();
    if (animIntervalRef.current) clearInterval(animIntervalRef.current);
    animIntervalRef.current = setInterval(() => {
      rotateIcon();
    }, 1200);
    request
      .sendCode(changeNumToDefault(num), altcha, typeof window !== "undefined" ? window.location.hostname : "")
      .then((response) => {
        clearInterval(animIntervalRef.current);
        animIntervalRef.current = null;
        if (response.uuid) {
          setUuid(response.uuid);
          handleTimer();
        }
      })
      .catch(() => {
        clearInterval(animIntervalRef.current);
        animIntervalRef.current = null;
        // challenge یک‌بارمصرف؛ برای تلاش بعدی تازه بگیر
        setAltcha("");
        setAltchaKey((k) => k + 1);
      });
  };

  return (
    <>
    <Altcha key={altchaKey} onVerified={setAltcha} />
    <Button
      className="flex !p-1 items-center justify-start gap-1 hover-rotate-90 cursor-pointer"
      disabled={typeof timer === "number" && timer !== 0}
      onClick={() => {
        if (!timer && timer !== "loading") {
          handleReq();
        }
      }}
    >
      {timer && timer !== "loading" ? (
        <p className="text-[#F17732] text-[14px] font-normal select-none">
          {timer} ثانیه
        </p>
      ) : (
        <>
          <div ref={retryIcon}>
            <RetryLogin />
          </div>
          <p className="text-[#F17732] text-[14px] font-normal select-none">
            دریافت مجدد کد
          </p>
        </>
      )}
    </Button>
    </>
  );
}

export default Recode;
