import { Button } from "@mui/material";
import { request } from "@/services/response";
import Cookies from "js-cookie";
import { handleTimeExpiresToken } from "@/helper";

function SendReq({
  loading,
  setLoading,
  code,
  setIsSendMsg,
  setStep,
  setIsError,
  uuid,
}) {
  const handleReq = async () => {
    setLoading(true);
    request
      .getToken(
        "mobile",
        process.env.NEXT_PUBLIC_CLIENT_ID,
        process.env.NEXT_PUBLIC_CLIENT_SECRET,
        uuid,
        code.join("")
      )
      .then((response) => {
        if (response.access_token) {
          handleSetCookie(response);
        }
      })
      .catch(() => {
        setLoading(false);
        setIsError(true);
      });
  };

  const handleSetCookie = (response) => {
    const expiresTime = handleTimeExpiresToken(response.expires_in);

    const hostname = window.location.hostname;
    const isHttps = window.location.protocol === "https:";
    const isLocalhost = hostname.includes("localhost");

    // تنظیمات پایه
    let cookieOptions = {
      path: "/",
      sameSite: "lax",
      expires: expiresTime.accessTokenExpires,
    };

    // اگر روی دامنه اصلی و https بود
    if (!isLocalhost && isHttps) {
      cookieOptions = {
        ...cookieOptions,
        secure: true,
        domain: ".nobat724.com",
      };
    }

    Cookies.set("access_token", response.access_token, cookieOptions);

    Cookies.set("refresh_token", response.refresh_token, {
      ...cookieOptions,
      expires: expiresTime.refreshTokenExpires,
    });

    Cookies.set("uuid", uuid, {
      ...cookieOptions,
      expires: expiresTime.refreshTokenExpires,
    });

    getInfo(response.access_token, cookieOptions);
  };

  const getInfo = (token, cookieOptions) => {
    request
      .getUserInfo({
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      .then((res) => {
        setLoading(false);
        if (res && res.uuid) {
          Cookies.set("userInfo", JSON.stringify(res), cookieOptions);
          window.location.pathname = "/";
        }
      })
      .catch(() => {
        setLoading(false);
        setIsError(true);
      });
  };

  return (
    <Button
      fullWidth
      disabled={loading}
      variant="contained"
      onClick={() => {
        setIsSendMsg && setIsSendMsg(true);
        setStep && setStep((prev) => prev + 1);
        if (code.join("").length !== 5) {
          setIsError(true);
        } else {
          handleReq();
        }
      }}
      className="!rounded-[8px] !bg-[#5559CE]"
    >
      تایید
    </Button>
  );
}

export default SendReq;
