import {
  useState,
  Suspense,
  lazy,
  createContext,
  useContext,
  useEffect,
} from "react";
import Breadcrumb from "../../components/common/Breadcrumb";
import { useFab } from "../../Context/FabContext";
import {
  useBucketList,
  useBuckets,
  useDeleteBucket,
} from "../../hooks/useDirectory";
import ManageBucket1 from "../../components/Directory/ManageBucket1";
import ManageContact from "../../components/Directory/ManageContact";
import BucketList from "../../components/Directory/BucketList";
import { MainDirectoryPageSkeleton } from "../../components/Directory/DirectoryPageSkeleton";
import ContactProfile from "../../components/Directory/ContactProfile";
import GlobalModel from "../../components/common/GlobalModel";
import { exportToCSV } from "../../utils/exportUtils";
import ConfirmModal from "../../components/common/ConfirmModal";
import { useSelectedProject } from "../../slices/apiDataManager";

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, projectId = null }) {
  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(false);
  const [isManageContact, setManageContact] = useState({
    isOpen: false,
    contactId: null,
  });
  const [deleteBucket, setDeleteBucket] = useState({
    isOpen: false,
    bucketId: null,
  });
  const [showActive, setShowActive] = useState(true);
  const [contactOpen, setContactOpen] = useState({
    contact: null,
    Open: false,
  });

  const [notesData, setNotesData] = useState([]);
  const [ContactData, setContactData] = useState([]);

  const handleExport = (type) => {
    if (activeTab === "notes" && type === "csv") {
      exportToCSV(notesData, "notes.csv");
    }
    if (activeTab === "contacts" && type === "csv") {
      exportToCSV(ContactData, "contact.csv");
    }
  };

  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,
    setContactOpen,
    setDeleteBucket,
  };

  const { mutate: DeleteBucket, isPending: Deleting } = useDeleteBucket(() => {
    setDeleteBucket({ isOpen: false, bucketId: null });
  });
  const handleDelete = (bucketId) => {
    DeleteBucket(bucketId);
  };
  if (isLoading) return <MainDirectoryPageSkeleton />;
  if (isError) return <div>{error.message}</div>;
  return (
    <>
      <DirectoryContext.Provider value={contextValues}>
        <div className={`${IsPage ? "container-fluid" : ""}`}>
          {IsPage && (
            <Breadcrumb
              data={[
                { label: "Home", link: "/dashboard" },
                { label: "Directory", link: null },
              ]}
            ></Breadcrumb>
          )}
          <div className="card">
            <div className="d-flex-row px-2">
              <div className="d-flex justify-content-between align-items-center mb-1">
                <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-notepad 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>

              <div className="mb-1 px-md-2 px-0 py-3">
                <div className="row">
                  <div className="col-12 col-md-10 mb-2">
                    {activeTab === "notes" && (
                      <div className="col-8 col-md-3">
                        <input
                          type="search"
                          className="form-control form-control-sm"
                          placeholder="Search notes..."
                          value={searchNote}
                          onChange={(e) => setSearchNote(e.target.value)}
                        />
                      </div>
                    )}

                    {activeTab === "contacts" && (
                      <div className="d-flex align-items-center gap-3">
                        <div className="col-12 col-md-8 d-flex flex-row gap-2">
                          <div className="col-7 col-md-4">
                            <input
                              type="search"
                              className="form-control form-control-sm"
                              placeholder="Search contacts..."
                              value={searchContact}
                              onChange={(e) => setsearchContact(e.target.value)}
                            />
                          </div>
                           <button
                            className={`btn btn-sm p-1 ${gridView ? " btn-primary" : " btn-outline-primary"
                              }`}
                            onClick={() => setGridView(true)}
                          >
                            <i className="bx bx-grid-alt"></i>
                          </button>
                          <button
                            className={`btn btn-sm p-1 ${!gridView ? "btn-primary" : "btn-outline-primary"
                              }`}
                            onClick={() => setGridView(false)}
                          >
                            <i className="bx bx-list-ul"></i>
                          </button>
                         
                          <div className="form-check form-switch d-flex align-items-end d-none d-md-flex">
                            <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-2"
                              htmlFor="inactiveEmployeesCheckbox"
                            >
                              {showActive ? "Active" : "In-active"} Contacts
                            </label>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                  <div className="col-12 col-md-2 d-flex justify-content-end align-items-center gap-2">
                    <div className="  btn-group">
                      <button
                        className="btn btn-sm btn-label-secondary dropdown-toggle"
                        type="button"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                      >
                        <i className="bx bx-export me-2 bx-sm"></i>Export
                      </button>
                      <ul className="dropdown-menu">
                        <li>
                          <a
                            className="dropdown-item cursor-pointer"
                            onClick={() => handleExport("csv")}
                          >
                            <i className="bx bx-file me-1"></i> CSV
                          </a>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div>
            <Suspense fallback={<MainDirectoryPageSkeleton />}>
              {activeTab === "notes" && (
                <NotesPage
                  projectId={projectId}
                  searchText={searchNote}
                  onExport={setNotesData}
                />
              )}
              {activeTab === "contacts" && (
                <ContactsPage
                  projectId={projectId}
                  searchText={searchContact}
                  onExport={setContactData}
                />
              )}
            </Suspense>
          </div>

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

          {contactOpen.Open && (
            <GlobalModel
              size="xl"
              isOpen={contactOpen.Open}
              closeModal={() => setContactOpen({ contact: null, Open: false })}
            >
              <ContactProfile contactId={contactOpen.contact} />
            </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>
          )}

          {deleteBucket.isOpen && (
            <ConfirmModal
              isOpen={deleteBucket.isOpen}
              type="delete"
              header="Delete Bucket"
              message="Are you sure you want delete?"
              onSubmit={handleDelete}
              onClose={() => setDeleteBucket({ isOpen: false, bucketId: null })}
              loading={Deleting}
              paramData={deleteBucket.bucketId}
            />
          )}
        </div>
      </DirectoryContext.Provider>
    </>
  );
}
