import { useState } from "react";
import ButtonFixed from "../paying/ButtonFixed";
import { Button } from "@mui/material";
import ArrowLeftB from "@/components/icons/ArrowLeftB";
import { request } from "@/services/response";

function SubmitData({ setStep, data, prevData }) {
  const [loading, setLoading] = useState(false);
  const newStep = () => setStep((prev) => prev + 1);

  const handleSubmit = () => {
    const isChanged = JSON.stringify(prevData) !== JSON.stringify(data);

    if (isChanged) {
      setLoading(true);
      let newData = data;
      const { basic_insurance, name, national_code, uuid } = newData;

      newData = {
        basic_insurance: [basic_insurance.value?.id],
        ...(prevData.name?.value === data.name.value ? {} : { name: name }),
        ...(prevData.national_code?.value
          ? {}
          : { national_code: national_code }),
      };

      request
        .patchUserProfile(newData, uuid)
        .then(() => {
          setLoading(false);
          newStep();
        })
        .catch(() => {
          setLoading(false);
        });
    } else {
      newStep();
    }
  };

  return (
    <ButtonFixed>
      <Button
        loading={loading}
        className={`
            !flex !w-full md:!w-fit !mt-0 md:!mt-[32px]
            !gap-[4px] md:!mr-auto !px-[12px] !py-[8px] md:!py-[9px] !min-w-[150px]
        `}
        variant="contained"
        onClick={handleSubmit}
      >
        <p
          className={`${loading && "opacity-0"} text-[#EFEFEF] text-[16px] font-medium`}
        >
          ثبت اطلاعات
        </p>
        <ArrowLeftB />
      </Button>
    </ButtonFixed>
  );
}

export default SubmitData;
