import React, { useEffect, useState } from "react";
import { useFab } from "../../Context/FabContext";
import { useContactList } from "../../hooks/useDirectory";
import { useDirectoryContext } from "./DirectoryPage";
import CardViewContact from "../../components/Directory/CardViewContact";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import ContactFilterPanel from "./ContactFilterPanel";
import { defaultContactFilter } from "../../components/Directory/DirectorySchema";
import { useDebounce } from "../../utils/appUtils";
import Pagination from "../../components/common/Pagination";
import ListViewContact from "../../components/Directory/ListViewContact";
import { CardViewContactSkeleton, ListViewContactSkeleton } from "../../components/Directory/DirectoryPageSkeleton";


const ContactsPage = ({projectId ,searchText }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [filters, setFilter] = useState(defaultContactFilter);
  const debouncedSearch = useDebounce(searchText, 500);
  const { showActive, gridView } = useDirectoryContext();
  const { data, isError, isLoading, error } = useContactList(
    showActive,
    projectId,
    ITEMS_PER_PAGE,
    currentPage,
    filters,
    debouncedSearch
  );
  const { setOffcanvasContent, setShowTrigger } = useFab();
  const clearFilter = () => {
    setFilter(defaultContactFilter);
  };
  useEffect(() => {
    setShowTrigger(true);
    setOffcanvasContent(
      "Contacts Filters",
      <ContactFilterPanel onApply={setFilter} clearFilter={clearFilter} />
    );

    return () => {
      setShowTrigger(false);
      setOffcanvasContent("", null);
    };
  }, []);

  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  if (isError) return <div>{error.message}</div>;
  if (isLoading) return <ListViewContactSkeleton/>;
  return (
 <div className="row mt-5">
  {gridView ? (
    <>
      {data?.data?.map((contact) => (
        <div
          key={contact.id}
          className="col-12 col-sm-6 col-md-4 col-lg-4 mb-4"
        >
          <CardViewContact IsActive={showActive} contact={contact} />
        </div>
      ))}

      {data?.data?.length > 0 && (
        <div className="col-12 d-flex justify-content-start mt-3">
          <Pagination
            currentPage={currentPage}
            totalPages={data.totalPages}
            onPageChange={paginate}
          />
        </div>
      )}
    </>
  ) : (
    <div className="col-12">
      <ListViewContact
        data={data.data}
        Pagination={
          <Pagination
            currentPage={currentPage}
            totalPages={data.totalPages}
            onPageChange={paginate}
          />
        }
      />
    </div>
  )}
</div>

  

)
};

export default ContactsPage;
