import React, { useState, useEffect } from "react";

import CreateRole from "./CreateRole";
import DeleteMaster from "./DeleteMaster";
import EditRole from "./EditRole";
import CreateJobRole from "./CreateJobRole";
import EditJobRole from "./EditJobRole";
import CreateActivity from "./CreateActivity";
import EditActivity from "./EditActivity";
import ConfirmModal from "../common/ConfirmModal";
import { MasterRespository } from "../../repositories/MastersRepository";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import showToast from "../../services/toastService";
import CreateWorkCategory from "./CreateWorkCategory";
import EditWorkCategory from "./EditWorkCategory";
import CreateCategory from "./CreateContactCategory";
import CreateContactTag from "./CreateContactTag";
import EditContactCategory from "./EditContactCategory";
import EditContactTag from "./EditContactTag";
import { useDeleteMasterItem } from "../../hooks/masterHook/useMaster";

const MasterModal = ({ modaldata, closeModal }) => {
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const { mutate: deleteMasterItem, isPending } = useDeleteMasterItem();

  // const handleSelectedMasterDeleted = async () =>
  // {
  //   debugger
  //   const deleteFn = MasterRespository[modaldata.masterType];
  //   if (!deleteFn) {
  //     showToast(`No delete strategy defined for master type`,"error");
  //     return false;
  //   }
  //    try
  //    {
  //      const response = await deleteFn( modaldata?.item?.id );
  //      const selected_cachedData = getCachedData( modaldata?.masterType );
  //      const updated_master =  selected_cachedData?.filter(item => item.id !== modaldata?.item.id);
  //      cacheData( modaldata?.masterType, updated_master )

  //      showToast(`${modaldata?.masterType} is deleted successfully`, "success");
  //      handleCloseDeleteModal()

  //    } catch ( error )
  //    {
  //      const message = error.response.data.message || error.message || "Error occured api during call"
  //      showToast(message, "success");
  //   }
  // }

  const handleSelectedMasterDeleted = () => {
    if (!modaldata?.masterType || !modaldata?.item?.id) {
      showToast("Missing master type or item", "error");
      return;
    }
    deleteMasterItem(
      {
        masterType: modaldata.masterType,
        item: modaldata.item,
        validateFn: modaldata.validateFn, // optional
      },
      {
        onSuccess: () => {
          handleCloseDeleteModal();
        },
      }
    );
  };

  useEffect(() => {
    if (modaldata?.modalType === "delete") {
      setIsDeleteModalOpen(true);
    }
  }, [modaldata]);

  const handleCloseDeleteModal = () => {
    setIsDeleteModalOpen(false);
    closeModal();
  };

  if (modaldata?.modalType === "delete" && isDeleteModalOpen) {
    return (
      <div
        className="modal fade show"
        tabIndex="-1"
        role="dialog"
        style={{ display: "block", backgroundColor: "rgba(0,0,0,0.5)" }}
        aria-hidden="false"
      >
        <ConfirmModal
          type="delete"
          header={`Delete ${modaldata.masterType}`}
          message={"Are you sure you want delete?"}
          onSubmit={handleSelectedMasterDeleted}
          onClose={handleCloseDeleteModal}
        />
      </div>
    );
  }
  return (
    <div
      className="modal fade"
      id="master-modal"
      tabIndex="-1"
      aria-hidden="true"
      role="dialog"
      aria-labelledby="modalToggleLabel"
    >
      <div
        className={`modal-dialog mx-sm-auto mx-1 ${
          ["Application Role", "Edit-Application Role"].includes(
            modaldata?.modalType
          )
            ? "modal-lg"
            : "modal-md"
        } modal-simple`}
      >
        <div className="modal-content">
          <div className="modal-body p-sm-4 p-0">
            <div className="d-flex justify-content-between">
              <h6>{`${modaldata?.modalType} `}</h6>
              <button
                type="button"
                className="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"
                onClick={closeModal}
              ></button>
            </div>

            {modaldata.modalType === "Application Role" && (
              <CreateRole
                masmodalType={modaldata.masterType}
                onClose={closeModal}
              />
            )}
            {modaldata.modalType === "Edit-Application Role" && (
              <EditRole master={modaldata} onClose={closeModal} />
            )}
            {modaldata.modalType === "Job Role" && (
              <CreateJobRole onClose={closeModal} />
            )}
            {modaldata.modalType === "Edit-Job Role" && (
              <EditJobRole data={modaldata.item} onClose={closeModal} />
            )}
            {modaldata.modalType === "Activity" && (
              <CreateActivity onClose={closeModal} />
            )}
            {modaldata.modalType === "Edit-Activity" && (
              <EditActivity
                activityData={modaldata.item}
                onClose={closeModal}
              />
            )}
            {modaldata.modalType === "Work Category" && (
              <CreateWorkCategory onClose={closeModal} />
            )}
            {modaldata.modalType === "Edit-Work Category" && (
              <EditWorkCategory data={modaldata.item} onClose={closeModal} />
            )}
            {modaldata.modalType === "Contact Category" && (
              <CreateCategory data={modaldata.item} onClose={closeModal} />
            )}
            {modaldata.modalType === "Edit-Contact Category" && (
              <EditContactCategory data={modaldata.item} onClose={closeModal} />
            )}
            {modaldata.modalType === "Contact Tag" && (
              <CreateContactTag data={modaldata.item} onClose={closeModal} />
            )}
            {modaldata.modalType === "Edit-Contact Tag" && (
              <EditContactTag data={modaldata.item} onClose={closeModal} />
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default MasterModal;
