import ArrowLeftWhiteD from "@/components/icons/ArrowLeftWhiteD";
import {
  changeDateType,
  handleTimeExpiresToken,
  removeAdditionalKeysDashboard,
} from "@/helper";
import { request } from "@/services/response";
import { Button } from "@mui/material";
import Cookies from "js-cookie";

function ButtonSendData({
  loading,
  errors,
  information,
  setInformation,
  setLoading,
  setErrors,
}) {
  const handleErrReq = (err) => {
    const errors = err?.response?.data;
    if (errors) {
      setErrors(typeof errors === "string" ? {} : errors);
    }
    setLoading(false);
  };

  const postData = () => {
    request
      .postUserProfile(changeDateType(information, false))
      .then((response) => {
        if (response.uuid) {
          const formData = new URLSearchParams();
          formData.append("grant_type", "refresh_token");
          formData.append("client_id", process.env.NEXT_PUBLIC_CLIENT_ID);
          formData.append(
            "client_secret",
            process.env.NEXT_PUBLIC_CLIENT_SECRET
          );
          formData.append("refresh_token", Cookies.get("refresh_token"));

          request
            .postRefreshToken(formData)
            .then((res) => {
              const expiresTime = handleTimeExpiresToken(res.expires_in);
              Cookies.set("access_token", res.access_token, {
                expires: expiresTime.accessTokenExpires,
                path: "/",
                secure: true,
                sameSite: "strict",
              });

              setInformation({
                ...information,
                prev_data: true,
                uuid: response.uuid,
              });
              setLoading(false);
            })
            .catch((err) => {
              setLoading(false);
            });
        }
      })
      .catch((err) => {
        handleErrReq(err);
      });
  };

  const patchData = () => {
    const usedKays = removeAdditionalKeysDashboard(information);

    request
      .patchUserProfile(
        changeDateType(usedKays, true),
        information?.uuid,
        Cookies.get("access_token")
      )
      .then(() => {
        setLoading(false);
      })
      .catch((err) => handleErrReq(err));
  };

  const sendReq = () => {
    setLoading(true);

    information.prev_data ? patchData() : postData();
  };
  const isDisabled = () => {
    return loading || Object.values(errors).some(Boolean) || !information;
  };

  return (
    <Button
      variant="contained"
      onClick={sendReq}
      loading={loading}
      disabled={isDisabled()}
      className={`!gap-[4px] !mr-auto !text-nowrap !flex !flex-nowrap !py-[8px]
                 !rounded-[4px] !text-[14px] md:!text-[16px] !font-medium
                !mt-[32px] sm:!mt-[38px] md:!mt-[43px] lg:!mt-[48px] !px-[16px] sm:!px-[19px] md:!px-[22px] lg:!px-[24px]
              `}
    >
      ثبت اطلاعات
      <ArrowLeftWhiteD />
    </Button>
  );
}

export default ButtonSendData;
