import ArrowLeftWhiteD from "@/components/icons/ArrowLeftWhiteD";
import {
  changeDateType,
  isValidIranNationalCode,
  removeAdditionalKeysDashboard,
} from "@/helper";
import { request } from "@/services/response";
import { Button, CircularProgress } from "@mui/material";
import { toast } from "react-toastify";
import { setAccessToken } from "@/lib/tokenStore";

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, true))
      .then((response) => {
        if (response.uuid) {
          fetch("/api/auth/refresh", { method: "POST" })
            .then((r) => (r.ok ? r.json() : null))
            .then((res) => {
              if (res?.access_token) {
                setAccessToken(res.access_token);
              }
              setInformation({
                ...information,
                prev_data: true,
                uuid: response.uuid,
              });
              setLoading(false);
              toast.success("اطلاعات با موفقیت ثبت شد");
            })
            .catch(() => {
              setLoading(false);
            });
        }
      })
      .catch((err) => {
        handleErrReq(err);
      });
  };

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

    request
      .patchUserProfile(changeDateType(usedKays, true), information?.uuid)
      .then(() => {
        setLoading(false);
        toast.success("اطلاعات با موفقیت ثبت شد");
      })
      .catch((err) => handleErrReq(err));
  };

  const sendReq = () => {
    if (information?.national_code && !isValidIranNationalCode(information.national_code)) {
      setErrors((prev) => ({ ...prev, national_code: true }));
      toast.error("کد ملی وارد شده معتبر نیست");
      return;
    }

    setLoading(true);

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

  return (
    <Button
      variant="contained"
      onClick={sendReq}
      disabled={loading || 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] `}
    >
      {loading ? (
        <CircularProgress size={20} sx={{ color: "#fff" }} />
      ) : (
        <>
          ثبت اطلاعات
          <ArrowLeftWhiteD />
        </>
      )}
    </Button>
  );
}

export default ButtonSendData;
