import ArrowLeftPA from "@/components/icons/ArrowLeftPA";
import { alert, checkAllValues } from "@/helper";
import { request } from "@/services/response";
import { Button } from "@mui/material";
import { useState } from "react";
import { transformData } from "./function";

function SendReq({ img, data, resetData }) {
  const [loading, setLoading] = useState(false);

  const saveData = (img) => {
    let transformed = transformData(data);

    if (img) {
      transformed.image = [img];
    }

    request
      .postDoctor(transformed)
      .then((res) => {
        if (res.id) {
          alert("success", "پزشک جدید با موفقیت اضافه شد!");
          resetData();
          setLoading(false);
        }
      })
      .catch(() => {
        setLoading(false);
        alert("error", "خطا در ثبت پزشک! لطفاً دوباره تلاش کنید.");
      });
  };

  const saveImg = () => {
    resetData();
    setLoading(true);
    if (img) {
      request
        .postImageUpload(img.file)
        .then((res) => {
          const imgId = res.fid[0].value;
          saveData(imgId);
        })
        .catch(() => {
          setLoading(false);
        });
    } else {
      saveData();
    }
  };

  return (
    <div className="mt-[40px] w-full flex justify-end">
      <Button
        className="!w-full md:!w-fit !shadow-none !rounded-[4px] !gap-[4px] !text-[#EFEFEF] !text-[14px] md:!text-[16px] !font-medium"
        disabled={!checkAllValues(data)}
        variant="contained"
        onClick={saveImg}
        loading={loading}
      >
        <p className={loading ? "opacity-0" : ""}>ثبت اطلاعات</p>
        <div className={!checkAllValues(data) ? "opacity-40" : "opacity-100"}>
          <ArrowLeftPA />
        </div>
      </Button>
    </div>
  );
}

export default SendReq;
