import React, { useState, useEffect } from "react";
import Breadcrumb from "../../components/common/Breadcrumb";
import MasterModal from "../../components/master/MasterModal";
import {  mastersList} from "../../data/masters";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster } from "../../slices/localVariablesSlice";
import useMaster from "../../hooks/masterHook/useMaster"
import MasterTable from "./MasterTable";
import { getCachedData } from "../../slices/apiDataManager";
import {useHasUserPermission} from "../../hooks/useHasUserPermission";
import { MANAGE_MASTER } from "../../utils/constants";


const MasterPage = () => {

  const [modalConfig, setmodalConfig] = useState({modalType: "", item: null, masterType:null });
  const [searchTerm, setSearchTerm] = useState('');
  const [ filteredResults, setFilteredResults ] = useState( [] );
  const hasMasterPermission = useHasUserPermission( MANAGE_MASTER )
  const dispatch = useDispatch();
  const selectedMaster = useSelector((store)=>store.localVariables.selectedMaster)
 
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  
  const openModal = () => {
    setIsCreateModalOpen(true);

  };

  const closeModal = () => {
    setIsCreateModalOpen(false); 
    setmodalConfig(null);
  
    
    const modalElement = document.getElementById('master-modal');
    if (modalElement) {
      modalElement.classList.remove('show'); 
      modalElement.style.display = 'none'; 
      document.body.classList.remove('modal-open'); 
  
    
      const backdropElement = document.querySelector('.modal-backdrop');
      if (backdropElement) {
        backdropElement.classList.remove('modal-backdrop'); 
        backdropElement.style.display = 'none'; 
      }
    }
    const modalBackdropElement = document.querySelector('.modal-backdrop');
    if (modalBackdropElement) {
      modalBackdropElement.remove(); 
    }
    document.body.style.overflow = 'auto';
   
  };
  

  const {data:masterData,  loading,error , RecallApi} = useMaster();

 

  const handleSearch = (e) => {
    const value = e.target.value.toLowerCase();
    setSearchTerm(value);
  
    if (!masterData.length) return;
  
    const results = masterData.filter((item) =>
      Object.values(item).some((field) => 
        field && field.toString().toLowerCase().includes(value) 
      )
    );
  
    setFilteredResults(results);
  };

  const displayData = searchTerm ? filteredResults : getCachedData(selectedMaster) ?  getCachedData(selectedMaster) : masterData

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

   const handleModalData =(modalType,item,masterType = selectedMaster)=>{
    setmodalConfig({ modalType: modalType, item:item,masterType:masterType });
  }

  useEffect(() => {
    if (modalConfig !== null) {
      openModal();
    }

  }, [ modalConfig, isCreateModalOpen ] );
  

  useEffect(() => {
    return () => {
      setIsCreateModalOpen(false)
      closeModal();
    };
  }, [])

  return (
    <>
      {isCreateModalOpen && (
          <MasterModal modaldata={modalConfig} closeModal={closeModal}    />
       
      )}

      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Masters", link: null },
          ]}
        ></Breadcrumb>
        <div className="row">
          <div className="card">
            <div className="card-datatable table-responsive pt-2">
              <div
                id="DataTables_Table_0_wrapper"
                className="dataTables_wrapper dt-bootstrap5 no-footer"
                style={{ width: "98%" }}
              >
                <div className="row  mb-2">
                  <div className="col-md-3 col-sm-6">
                    <div className="ms-0">
                      <div
                        className="dataTables_length text-start"
                        id="DataTables_Table_0_length"
                      >
                        <label>
                          <select
                            onChange={(e) => dispatch(changeMaster(e.target.value))} 
                            name="DataTables_Table_0_length"
                            aria-controls="DataTables_Table_0"
                            className="form-select form-select-sm"
                            value={selectedMaster}
                          >

                            {mastersList.map( ( item ) => (
                              
                              <option key={item.id} value={item.name}>{item.name}</option>
                            ))}
                          </select>
                        </label>
                      </div>
                    </div>
                  </div>
                  <div className="col-md-9 col-sm-6">
                    <div className="dt-action-buttons text-xl-end text-lg-start text-md-end text-start d-flex align-items-center justify-content-sm-end justify-content-between gap-2 flex-md-row flex-sm-column mb-3 mb-md-0 mt-1 mt-md-0 gap-md-4">
                      <div
                        id="DataTables_Table_0_filter"
                        className="dataTables_filter"
                      >
                        <label>
                          <input
                            type="search"
                            className="form-control form-control-sm"
                            placeholder="Search"
                            aria-controls="DataTables_Table_0"
                            value={searchTerm}
                            onChange={handleSearch}
                          ></input>
                        </label>
                      </div>
                      <div className={`dt-buttons btn-group flex-wrap ${!hasMasterPermission && 'd-none'}`}>
                        {" "}
                        <div className="input-group">
                
                          <button
                            className={`btn btn-sm  add-new btn-primary `}
                            // ${hasUserPermission('660131a4-788c-4739-a082-cbbf7879cbf2') ? "":"d-none"}
                            tabIndex="0"
                            aria-controls="DataTables_Table_0"
                            type="button"
                            data-bs-toggle="modal"
                            data-bs-target="#master-modal"
                            onClick={() => {
                              handleModalData(selectedMaster,"null",selectedMaster)
                              
                            }}
                          >
                            <span>
                              <i className="bx bx-plus-circle me-2"></i>
                              <span className=" d-sm-inline-block">
                                Add  {selectedMaster}
                              </span>
                            </span>
                          </button>{" "}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
               
                <MasterTable data={displayData} columns={columns} loading={loading} handleModalData={handleModalData} />
                <div style={{ width: "1%" }}></div>
              </div>
            </div>
          </div>
        </div>

      </div>
    </>
  );
};

export default MasterPage;
