import React, { useEffect, useState, useMemo } from "react";
import { DirectoryRepository } from "../../repositories/DirectoryRepository";
import NoteCardDirectoryEditable from "./NoteCardDirectoryEditable";

const NotesCardViewDirectory = ({ notes, setNotesForFilter, searchText, filterAppliedNotes }) => {
  const [allNotes, setAllNotes] = useState([]);
  const [filteredNotes, setFilteredNotes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedCreators, setSelectedCreators] = useState([]);
  const [selectedOrgs, setSelectedOrgs] = useState([]);
  const pageSize = 20;

  useEffect(() => {
    fetchNotes();
  }, []);

  const fetchNotes = async () => {
    setLoading(true);
    try {
      const response = await DirectoryRepository.GetNotes(1000, 1);
      const fetchedNotes = response.data?.data || [];
      setAllNotes(fetchedNotes);
      setNotesForFilter(fetchedNotes)

      const creatorsSet = new Set();
      const orgsSet = new Set();

      fetchedNotes.forEach((note) => {
        const creator = `${note.createdBy?.firstName || ""} ${note.createdBy?.lastName || ""}`.trim();
        if (creator) creatorsSet.add(creator);

        const org = note.organizationName;
        if (org) orgsSet.add(org);
      });

    } catch (error) {
      console.error("Failed to fetch notes:", error);
    } finally {
      setLoading(false);
    }
  };



  const applyCombinedFilter = () => {
    const lowerSearch = searchText?.toLowerCase() || "";

    const filtered = allNotes.filter((noteItem) => {
      const creator = `${noteItem.createdBy?.firstName || ""} ${noteItem.createdBy?.lastName || ""}`.trim();
      const org = noteItem.organizationName;

      const matchesCreator = selectedCreators.length === 0 || selectedCreators.includes(creator);
      const matchesOrg = selectedOrgs.length === 0 || selectedOrgs.includes(org);

      const plainNote = noteItem?.note?.replace(/<[^>]+>/g, "").toLowerCase();

      const stringValues = [];
      const extractStrings = (obj) => {
        for (const key in obj) {
          const value = obj[key];
          if (typeof value === "string") {
            stringValues.push(value.toLowerCase());
          } else if (typeof value === "object" && value !== null) {
            extractStrings(value);
          }
        }
      };
      extractStrings(noteItem);
      stringValues.push(plainNote, creator.toLowerCase());

      const matchesSearch = stringValues.some((val) => val.includes(lowerSearch));

      return matchesCreator && matchesOrg && matchesSearch;
    });

    setFilteredNotes(filtered);
    setCurrentPage(1);
    setTotalPages(Math.ceil(filtered.length / pageSize));
  };

  useEffect(() => {
    applyCombinedFilter();
  }, [searchText, allNotes]);

  useEffect(() => {
    setFilteredNotes(filterAppliedNotes);
  }, [filterAppliedNotes])

  const currentItems = useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    return filteredNotes.slice(startIndex, startIndex + pageSize);
  }, [filteredNotes, currentPage]);

  const handlePageClick = (page) => {
    if (page !== currentPage) {
      setCurrentPage(page);
    }
  };

  if (loading) return <p className="mt-10 text-center">Loading notes...</p>;

  if (!filteredNotes.length) return <p className="mt-10 text-center">No matching notes found</p>;


  return (
    <div className="w-100 h-100 ">
      {/* Filter Dropdown */}
      <div className="dropdown mb-3 ms-2">    
      </div>

      {/* Notes List */}
      <div className="d-flex flex-column text-start" style={{ gap: "0rem", minHeight: "100%" }}>
        {currentItems.map((noteItem) => (
          <NoteCardDirectoryEditable
            key={noteItem.id}
            noteItem={noteItem}
            contactId={noteItem.contactId}
            onNoteUpdate={(updatedNote) => {
              setAllNotes((prevNotes) =>
                prevNotes.map((n) => (n.id === updatedNote.id ? updatedNote : n))
              );
            }}
            onNoteDelete={() => fetchNotes()}
          />
        ))}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="d-flex justify-content-end mt-3 me-3">
          <div className="d-flex align-items-center gap-2">
            <button
              className="btn btn-sm rounded-circle border"
              onClick={() => handlePageClick(Math.max(1, currentPage - 1))}
              disabled={currentPage === 1}
              title="Previous"
            >
              «
            </button>

            {[...Array(totalPages)].map((_, i) => {
              const page = i + 1;
              return (
                <button
                  key={page}
                  className={`btn btn-sm rounded-circle border ${page === currentPage ? "btn-primary text-white" : "btn-outline-primary"
                    }`}
                  style={{ width: "32px", height: "32px", padding: 0 }}
                  onClick={() => handlePageClick(page)}
                >
                  {page}
                </button>
              );
            })}

            <button
              className="btn btn-sm rounded-circle border"
              onClick={() => handlePageClick(Math.min(totalPages, currentPage + 1))}
              disabled={currentPage === totalPages}
              title="Next"
            >
              »
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default NotesCardViewDirectory;
