import React, { useState, useMemo, useEffect, createContext, useContext } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useQueryClient } from "@tanstack/react-query";
import Breadcrumb from "../../components/common/Breadcrumb";
import MasterModal from "../../components/master/MasterModal";
import ConfirmModal from "../../components/common/ConfirmModal";
import MasterTable from "./MasterTable";
import useMaster, {
  useDeleteActivity,
  useDeleteMasterItem,
  useDeleteServiceGroup,
  useMasterMenu,
} from "../../hooks/masterHook/useMaster";
import { changeMaster } from "../../slices/localVariablesSlice";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { MANAGE_MASTER } from "../../utils/constants";
import GlobalModel from "../../components/common/GlobalModel";


export const MasterContext = createContext();
export const useMasterContext = () => {
  const context = useContext(MasterContext);
  if (!context) {
    throw new Error("useMasterContext must be used within an MasterProvider");
  }
  return context;
};

const MasterPage = () => {
  const dispatch = useDispatch();
  const queryClient = useQueryClient();
  const selectedMaster = useSelector(
    (store) => store.localVariables.selectedMaster
  );
  const hasMasterPermission = useHasUserPermission(MANAGE_MASTER);

  const {
    data: menuData,
    isLoading: menuLoading,
    isError: menuErrorFlag,
    error: menuError,
  } = useMasterMenu();
  const {
    data: masterData = [],
    loading,
    isError: isMasterError,
  } = useMaster();
  const { mutate: DeleteMaster, isPending: isDeleting } = useDeleteMasterItem();
  const [isDeleletingServiceItem,setDeleletingServiceItem] = useState({isOpen:false,ItemId:null,whichItem:null})
  const {mutate:DeleteSericeGroup,isPending:deletingGroup}  =useDeleteServiceGroup()
  const {mutate:DeleteAcivity,isPending:deletingActivity} = useDeleteActivity()

  const [modalConfig, setModalConfig] = useState(null);
  const [deleteData, setDeleteData] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");

  const displayData = useMemo(() => {
    const dataSource =
      queryClient.getQueryData(["masterData", selectedMaster]) || masterData;
    if (!searchTerm) return dataSource;
    return dataSource.filter((item) =>
      Object.values(item).some((val) =>
        val?.toString().toLowerCase().includes(searchTerm.toLowerCase())
      )
    );
  }, [searchTerm, masterData, selectedMaster, queryClient]);

  const columns = useMemo(() => {
    if (!displayData.length) return [];
    return Object.keys(displayData[0]).map((key) => ({
      key,
      label: key.toUpperCase(),
    }));
  }, [displayData]);

  const handleModalData = (type, item = null, masterType = selectedMaster) => {
    if (type === "delete") setDeleteData({ item, masterType });
    else setModalConfig({ modalType: type, item, masterType });
  };

  const handleDeleteSubmit = () => {
    if (!deleteData) return;
    DeleteMaster(
      { masterType: deleteData.masterType, item: deleteData.item },
      {
        onSuccess: () => setDeleteData(null),
      }
    );
  };


  const handleDeleteServiceItem =()=>{
    if(!isDeleletingServiceItem.ItemId) return
    debugger
    if(isDeleletingServiceItem.whichItem === "activity"){
        DeleteAcivity(isDeleletingServiceItem.ItemId,{onSuccess:()=>setDeleletingServiceItem({isOpen:false,ItemId:null,whichItem:null})})
    }else{
      DeleteSericeGroup(isDeleletingServiceItem.ItemId,{onSuccess:()=>setDeleletingServiceItem({isOpen:false,ItemId:null,whichItem:null})})
    }
  

  }

  if (menuErrorFlag || isMasterError)
    return (
      <div className="d-flex flex-column align-items-center justify-content-center py-5">
        <h4 className="mb-3">
          <i className="fa-solid fa-triangle-exclamation fs-5" /> Oops, an error
          occurred
        </h4>
        <p className="text-muted">
          {menuError?.message || "Error fetching master data"}
        </p>
      </div>
    );

  return (
    <MasterContext.Provider value={{setDeleletingServiceItem}}>
      {modalConfig && (
        <GlobalModel
          size={
            ["Application Role", "Edit-Application Role", "Services"].includes(
              modalConfig.masterType
            )
              ? "lg"
              : "md"
          }
          isOpen={!!modalConfig}
          closeModal={() => setModalConfig(null)}
        >
          <MasterModal
            modaldata={modalConfig}
            closeModal={() => setModalConfig(null)}
          />
        </GlobalModel>
      )}
      

      <ConfirmModal
        type="delete"
        header={`Delete ${selectedMaster}`}
        message={`Are you sure you want to delete this ${selectedMaster}?`}
        isOpen={!!deleteData}
        loading={isDeleting}
        onSubmit={handleDeleteSubmit}
        onClose={() => setDeleteData(null)}
      />
      
      <ConfirmModal
        type="delete"
        header={`Delete ${isDeleletingServiceItem?.whichItem}`}
        message={`Are you sure you want to delete this ${isDeleletingServiceItem?.whichItem}?`}
        isOpen={!!isDeleletingServiceItem?.isOpen}
        loading={deletingActivity}
            onSubmit={handleDeleteServiceItem}
        onClose={() => setDeleletingServiceItem({isOpen:false,ItemId:null,whichItem:null})}
      />

      <div className="container-fluid">
        <Breadcrumb
          data={[{ label: "Home", link: "/dashboard" }, { label: "Masters" }]}
        />


          <div className="card page-min-h">
            <div
              className="card-datatable table-responsive py-10 mx-5 "
              style={{ overflow: "hidden" }}
            >
              <div className="row mb-2">
                <div className="col-md-3 col-sm-6">
                  <select
                    className="form-select py-1 px-2"
                    style={{
                      fontSize: "0.875rem",
                      height: "32px",
                      width: "190px",
                    }}
                    value={selectedMaster}
                    onChange={(e) => dispatch(changeMaster(e.target.value))}
                  >
                    {menuLoading ? (
                      <option value="">Loading...</option>
                    ) : (
                      menuData?.map((item) => (
                        <option key={item.id} value={item.name}>
                          {item.name}
                        </option>
                      ))
                    )}
                  </select>
                </div>
                <div className="col-md-9 col-sm-6 d-flex justify-content-end align-items-center gap-2">
                  <div className="w-25">
                    <input
                      type="search"
                      className="form-control form-control-sm"
                      placeholder="Search"
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                    />
                  </div>
                  {hasMasterPermission && (
                    <button
                      className="btn btn-sm btn-primary"
                      onClick={() =>
                        handleModalData(selectedMaster, null, selectedMaster)
                      }
                    >
                      <i className="bx bx-plus-circle me-2"></i>Add{" "}
                      {selectedMaster}
                    </button>
                  )}
                </div>
              </div>

              <MasterTable
                data={displayData}
                columns={columns}
                loading={loading}
                handleModalData={handleModalData}
              />
            </div>
        </div>
      </div>
     </MasterContext.Provider>
  );
};

export default MasterPage;
