import RetryLogin from "@/components/icons/RetryLogin";
import { changeNumToDefault } from "@/helper";
import { request } from "@/services/response";
import { Button } from "@mui/material";
const time_resend_code = 120;

function Recode({ retryIcon, timer, setUuid, num, setTimer }) {
  const handleTimer = () => {
    setTimer("loading");
    setTimeout(() => {
      setTimer(time_resend_code);
      let timePresent = time_resend_code;
      const timerInterval = setInterval(() => {
        timePresent--;
        setTimer(timePresent);

        !timePresent && clearInterval(timerInterval);
      }, 1000);
    }, 1000);
  };

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

  const handleReq = () => {
    rotateIcon();
    const interval = setInterval(() => {
      rotateIcon();
    }, 1200);
    request
      .sendCode(changeNumToDefault(num), "")
      .then((response) => {
        clearInterval(interval);
        if (response.uuid) {
          setUuid(response.uuid);
          handleTimer();
        }
      })
      .catch(() => clearInterval(interval));
  };

  return (
    <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") {
          // handleTimer();
          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;
