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";
import ManageExpenseType from "./ManageExpenseType";
import ManagePaymentMode from "./ManagePaymentMode";
import ManageExpenseStatus from "./ManageExpenseStatus";


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

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

    deleteMasterItem(
      { masterType, item, validateFn },
      { onSuccess: handleCloseDeleteModal }
    );
  };

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

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

  if (!modaldata?.modalType) {
    closeModal();
    return null;
  }

  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>
    );
  }

  const renderModalContent = () => {
    const { modalType, item, masterType } = modaldata;

    const modalComponents = {
      "Application Role": <CreateRole masmodalType={masterType} onClose={closeModal} />,
      "Edit-Application Role": <EditRole master={modaldata} onClose={closeModal} />,
      "Job Role": <CreateJobRole onClose={closeModal} />,
      "Edit-Job Role": <EditJobRole data={item} onClose={closeModal} />,
      "Activity": <CreateActivity onClose={closeModal} />,
      "Edit-Activity": <EditActivity activityData={item} onClose={closeModal} />,
      "Work Category": <CreateWorkCategory onClose={closeModal} />,
      "Edit-Work Category": <EditWorkCategory data={item} onClose={closeModal} />,
      "Contact Category": <CreateCategory data={item} onClose={closeModal} />,
      "Edit-Contact Category": <EditContactCategory data={item} onClose={closeModal} />,
      "Contact Tag": <CreateContactTag data={item} onClose={closeModal} />,
      "Edit-Contact Tag": <EditContactTag data={item} onClose={closeModal} />,
      "Expense Type":<ManageExpenseType  onClose={closeModal} />,
      "Edit-Expense Type":<ManageExpenseType data={item} onClose={closeModal} />,
      "Payment Mode":<ManagePaymentMode onClose={closeModal}/>,
      "Edit-Payment Mode":<ManagePaymentMode data={item} onClose={closeModal}/>,
      "Expense Status":<ManageExpenseStatus onClose={closeModal}/>,
      "Edit-Expense Status":<ManageExpenseStatus data={item} onClose={closeModal}/>
    };

    return modalComponents[modalType] || null;
  };

  const isLargeModal = ["Application Role", "Edit-Application Role"].includes(
    modaldata.modalType
  );

  return (
    <div
      className="modal fade show"
      id="master-modal"
      tabIndex="-1"
      role="dialog"
      aria-hidden="true"
      aria-labelledby="modalToggleLabel"
      style={{ display: "block" }}
    >
      <div className={`modal-dialog mx-sm-auto mx-1 ${isLargeModal ? "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}
              />
            </div>
            {renderModalContent()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default MasterModal;
