import {
  useState,
  Suspense,
  lazy,
  createContext,
  useContext,
  useEffect,
} from "react";
import Breadcrumb from "../../components/common/Breadcrumb";
import { useFab } from "../../Context/FabContext";
import { useBucketList, useBuckets } from "../../hooks/useDirectory";
import GlobalModel from "../../components/common/GlobalModel";
import ManageBucket from "../../components/Directory/ManageBucket";
import ManageBucket1 from "../../components/Directory/ManageBucket1";
import ManageContact from "../../components/Directory/ManageContact";
import BucketList from "../../components/Directory/BucketList";

const NotesPage = lazy(() => import("./NotesPage"));
const ContactsPage = lazy(() => import("./ContactsPage"));

export const DirectoryContext = createContext();
export const useDirectoryContext = () => {
  const context = useContext(DirectoryContext);

  if (!context) {
    return (
      <div className="container-fluid">
        <p>Your Action is out of context</p>
      </div>
    );
  }
  return context;
};
export default function DirectoryPage({ IsPage = true }) {
  const [searchContact, setsearchContact] = useState("");
  const [searchNote, setSearchNote] = useState("");
  const [activeTab, setActiveTab] = useState("notes");
  const { setActions } = useFab();
  const [gridView, setGridView] = useState(false);
  const [isOpenBucket, setOpenBucket] = useState({});
  const [isManageContact, setManageContact] = useState({
    isOpen:false,contactId:null
  });
  const [showActive, setShowActive] = useState(true);

  const { data, isLoading, isError, error } = useBucketList();

  const handleTabClick = (tab, e) => {
    e.preventDefault();
    setActiveTab(tab);
  };

  useEffect(() => {
    const actions = [];

    if (IsPage) {
      actions.push({
        label: "Manage Bucket",
        icon: "fa-solid fa-bucket fs-5",
        color: "primary",
        onClick: () => setOpenBucket(true),
      });
    }
    if (data?.length > 0) {
      actions.push({
        label: "New Contact",
        icon: "bx bx-plus-circle",
        color: "warning",
        onClick: () => setManageContact({isOpen:true,contactId:null}),
      });
    }

    setActions(actions);

    return () => setActions([]);
  }, [IsPage, data]);

  const contextValues = {
    showActive,
    gridView,
    data,
    setManageContact
  };

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>{error.message}</div>;
  return (
    <>
      <DirectoryContext.Provider value={contextValues}>
        <div className="container-fluid">
          <Breadcrumb
            data={[
              { label: "Home", link: "/dashboard" },
              { label: "Directory", link: null },
            ]}
          ></Breadcrumb>
          <div className="card">
            <div className="d-flex justify-content-between align-items-center mb-1 px-2">
              <ul className="nav nav-tabs">
                <li className="nav-item cursor-pointer">
                  <a
                    className={`nav-link ${
                      activeTab === "notes" ? "active" : ""
                    } fs-6`}
                    onClick={(e) => handleTabClick("notes", e)}
                  >
                    <i className="bx bx-note bx-sm me-1_5"></i>
                    <span className="d-none d-md-inline">Notes</span>
                  </a>
                </li>
                <li className="nav-item cursor-pointer">
                  <a
                    className={`nav-link ${
                      activeTab === "contacts" ? "active" : ""
                    } fs-6`}
                    onClick={(e) => handleTabClick("contacts", e)}
                  >
                    <i className="bx bxs-contact bx-sm me-1_5"></i>
                    <span className="d-none d-md-inline">Contacts</span>
                  </a>
                </li>
              </ul>

              <div className="btn-group">
                <button
                  className="btn btn-sm btn-secondary dropdown-toggle"
                  type="button"
                  data-bs-toggle="dropdown"
                  aria-haspopup="true"
                  aria-expanded="false"
                >
                  <i className="bx bx-download"></i> Export
                </button>
                <ul className="dropdown-menu dropdown-menu-end">
                  <li>
                    <a className="dropdown-item">Action</a>
                  </li>
                  <li>
                    <a className="dropdown-item">Another action</a>
                  </li>
                </ul>
              </div>
            </div>

            <div className="mb-1 px-2">
              <div className="d-flex align-items-center justify-content-between">
                <div>
                  {activeTab === "notes" && (
                    <input
                      type="search"
                      className="form-control form-control-sm"
                      placeholder="Search notes..."
                      value={searchNote}
                      onChange={(e) => setSearchNote(e.target.value)}
                    />
                  )}

                  {activeTab === "contacts" && (
                    <div className="d-flex align-items-center">
                      <div className="d-flex gap-2 align-items-center">
                        <input
                          type="text"
                          className="form-control form-control-sm"
                          placeholder="Search contacts..."
                          value={searchContact}
                          onChange={(e) => setsearchContact(e.target.value)}
                        />
                        <button
                          className={`btn btn-xs ${
                            !gridView ? "btn-primary" : "btn-outline-secondary"
                          }`}
                          onClick={() => setGridView(false)}
                        >
                          <i className="bx bx-list-ul"></i>
                        </button>

                        <button
                          className={`btn btn-xs ${
                            gridView ? "btn-primary" : "btn-outline-secondary"
                          }`}
                          onClick={() => setGridView(true)}
                        >
                          <i className="bx bx-grid-alt"></i>
                        </button>
                      </div>
                      <div className="form-check form-switch text-start m-0 ms-5">
                        <input
                          type="checkbox"
                          className="form-check-input"
                          role="switch"
                          id="inactiveEmployeesCheckbox"
                          checked={showActive}
                          onChange={(e) => setShowActive(e.target.checked)}
                        />
                        <label className="form-check-label ms-0">
                          {showActive ? "In Active" : "Active"}
                        </label>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          <div>
            <Suspense
              fallback={
                <div className="text-center py-5">
                  <div className="spinner-border text-primary" role="status">
                    <span className="visually-hidden">Loading...</span>
                  </div>
                </div>
              }
            >
              {activeTab === "notes" && <NotesPage />}
              {activeTab === "contacts" && (
                <ContactsPage searchText={searchContact} />
              )}
            </Suspense>
          </div>

          {isOpenBucket && (
            <GlobalModel
              size="lg"
              isOpen={isOpenBucket}
              closeModal={() => setOpenBucket(false)}
            >
              <ManageBucket1 closeModal={() => setOpenBucket(false)} />
            </GlobalModel>
          )}

          {isManageContact.isOpen && (
            <GlobalModel
              size="lg"
              isOpen={isManageContact}
              closeModal={() => setManageContact({isOpen:false,contactId:null})}
            >
              <ManageContact contactId={isManageContact.contactId} closeModal={() => setManageContact({isOpen:false,contactId:null})} />
            </GlobalModel>
          )}
        </div>
      </DirectoryContext.Provider>
    </>
  );
}
