import React, { useEffect, useRef, useState } from "react";
import { useFab } from "../../Context/FabContext";
import { useNotes } from "../../hooks/useDirectory";
import NoteFilterPanel from "./NoteFilterPanel";
import { defaultNotesFilter } from "../../components/Directory/DirectorySchema";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import { useDebounce } from "../../utils/appUtils";
import NoteCardDirectoryEditable from "../../components/Directory/NoteCardDirectoryEditable";
import Pagination from "../../components/common/Pagination";
import { NoteCardSkeleton } from "../../components/Directory/DirectoryPageSkeleton";
import NoteFilterChips from "../../components/Directory/NoteFilterChips";

const NotesPage = ({ projectId, searchText, onExport }) => {
  const [filters, setFilter] = useState(defaultNotesFilter);
  const [currentPage, setCurrentPage] = useState(1);
  const debouncedSearch = useDebounce(searchText, 500);
  const [filterData, setFilterdata] = useState(null);
  const updatedRef = useRef();

  const { data, isLoading, isError, error } = useNotes(
    projectId,
    ITEMS_PER_PAGE,
    currentPage,
    filters,
    debouncedSearch
  );

  const { setOffcanvasContent, setShowTrigger } = useFab();

  const clearFilter = () => {
    setFilter(defaultNotesFilter);
  };

  useEffect(() => {
    setShowTrigger(true);
    setOffcanvasContent(
      "Notes Filters",
      <NoteFilterPanel
        ref={updatedRef} //Call here
        onApply={setFilter}
        clearFilter={clearFilter}
        setFilterdata={setFilterdata}
      />
    );

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

  const handleRemoveChip = (key, id) => {
    setFilter((prev) => {
      const updated = { ...prev };

      if (Array.isArray(updated[key])) {
        updated[key] = updated[key].filter((v) => v !== id);
        updatedRef.current?.resetFieldValue(key, updated[key]); //IMP
      } else {
        updated[key] = null;
        updatedRef.current?.resetFieldValue(key, null);
      }

      return updated;
    });
  };

  // Format data for export
  const formatExportData = (notes) => {
    return notes.map((n) => ({
      ContactName: n.contactName || "",
      Note: n.note ? n.note.replace(/<[^>]+>/g, "") : "",
      Organization: n.organizationName || "",
      CreatedBy: n.createdBy
        ? `${n.createdBy.firstName || ""} ${n.createdBy.lastName || ""}`.trim()
        : "",
      CreatedAt: n.createdAt ? new Date(n.createdAt).toLocaleString() : "",
      UpdatedBy: n.updatedBy
        ? `${n.updatedBy.firstName || ""} ${n.updatedBy.lastName || ""}`.trim()
        : "",
      UpdatedAt: n.updatedAt ? new Date(n.updatedAt).toLocaleString() : "",
    }));
  };

  useEffect(() => {
    if (data?.data && onExport) {
      onExport(formatExportData(data.data));
    }
  }, [data?.data]);

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

  if (isError) return <div>{error.message}</div>;
  if (isLoading) return <NoteCardSkeleton />;

  return (
    <div className="d-flex flex-column text-start mt-3">
      <NoteFilterChips
        filters={filters}
        filterData={filterData}
        removeFilterChip={handleRemoveChip}
      />

      {data?.data?.length > 0 ? (
        <>
          {data.data.map((noteItem) => (
            <NoteCardDirectoryEditable
              key={noteItem.id}
              noteItem={noteItem}
              contactId={noteItem.contactId}
            />
          ))}

          <div className="col-12 d-flex justify-content-start mt-3">
            <Pagination
              currentPage={currentPage}
              totalPages={data.totalPages}
              onPageChange={paginate}
            />
          </div>
        </>
      ) : (
        <div
          className="card text-center d-flex align-items-center justify-content-center"
          style={{ height: "200px" }}
        >
          <p className="text-muted mb-0">
            {debouncedSearch
              ? `No notes found matching "${searchText}"`
              : Object.keys(filters).some((k) => filters[k]?.length)
                ? "No notes found for the applied filters."
                : "No notes available."}
          </p>
        </div>
      )}
    </div>
  );
};

export default NotesPage;
