// import React, { useEffect, useState } from "react";
// import { getUsers } from "@/services/userService";
// import { toast } from "react-toastify";
// import Layout from "../../Layout";
// import EditUserModal from "../../components/admin/user-management/EditUserModal";
// import ChangeRoleModal from "../../components/admin/user-management/ChangeRoleModal";
// import { assetPath } from "../../utils/assetPath";
// import { useProfile } from "@/context/ProfileContext";

// function ManagementItem({ user, onEdit, onRoleChange }) {
//   const { profile } = useProfile();
//   // const isAnalyst = profile?.role_names?.includes("Analyst");
//   const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
//   const initials = user.details?.full_name
//     ? user.details.full_name
//       .split(" ")
//       .map((n) => n[0])
//       .join("")
//       .toUpperCase()
//     : "NA";

//   return (
//     <div className="managementlist">
//       <div className="media">
//         <div className="mnageuser">{initials}</div>
//         <div className="media-object">
//           <span className="mng-badge d-inline-flex d-sm-none">{user.role_details?.[0]?.name || "Unknown Role"}</span>
//           <h3>{user.details?.full_name || "Unknown User"}</h3>
//           <span>{user.details?.organization_name || "N/A"}</span>
//         </div>
//       </div>
//       <div className="d-none d-sm-inline-flex flex-column gap-1 align-items-center">
//         <span>Role</span>
//         <span
//           className={`mng-badge ${user.role_details?.[0]?.name === "Analyst"
//               ? "role-bg"
//               : user.role_details?.[0]?.name === "Admin"
//                 ? "role-bga"
//                 : user.role_details?.[0]?.name?.trim().toLowerCase() === "paralegal"
//                   ? "role-bgp"
//                   : ""
//             }`}
//         >
//           {user.role_details?.[0]?.name || "Unknown Role"}
//         </span>
//       </div>
//       <div className="manageactin">
//         {/* <span
//           className={
//             user.details?.status === "available" ? "actvetxt" : "inactivetxt"
//           }
//         >
//           {(user.details?.status || "unknown")
//             .charAt(0)
//             .toUpperCase() +
//             (user.details?.status || "unknown").slice(1).toLowerCase()}
//         </span> */}

//         <span
//           className={
//             user.details?.status === "available" ||
//               user.details?.status === "active"
//               ? "actvetxt"
//               : user.details?.status === "busy"
//                 ? "oflnetxt"
//                 : "oflnetxt"
//           }
//         >
//           {(user.details?.status || "unknown")
//             .charAt(0)
//             .toUpperCase() +
//             (user.details?.status || "unknown").slice(1).toLowerCase()}
//         </span>

//         {profile?.roles?.includes(5) && (
//           <div className="actindted">
//             <div className="dropdown">
//               <button
//                 className="dropdown-toggle"
//                 type="button"
//                 data-bs-toggle="dropdown"
//               >
//                 <img src={assetPath("/assets/images/dtedbig.png")} alt="" />

//               </button>

//               <ul className="dropdown-menu">

//                 <li style={{ cursor: "pointer" }}>
//                   <a onClick={() => onEdit(user.id)}>
//                     <i>
//                       <img src={assetPath("/assets/images/action_icn2.png")} alt="" />

//                     </i>
//                     Edit User
//                   </a>
//                 </li>

//                 <li style={{ cursor: "pointer" }}>
//                   <a onClick={() => onRoleChange(user.id)}>
//                     <i>
//                       <img src={assetPath("/assets/images/userrle.png")} alt="" />

//                     </i>
//                     Change Role
//                   </a>
//                 </li>

//               </ul>
//             </div>
//           </div>
//         )}
//       </div>
//     </div>
//   );
// }

// export default function UserManagement() {
//   const [users, setUsers] = useState([]);
//   const [loading, setLoading] = useState(true);
//   const [currentPage, setCurrentPage] = useState(1);
//   const usersPerPage = 10;
//   const [showEdit, setShowEdit] = useState(false);
//   const [selectedId, setSelectedId] = useState(null);
//   const [showRoleModal, setShowRoleModal] = useState(false);
//   const [search, setSearch] = useState("");

//   const loadUsers = async () => {
//     try {
//       setLoading(true);
//       const { data } = await getUsers();
//       setUsers(data || []);
//     } catch (err) {
//       toast.error("Failed to load users");
//     } finally {
//       setLoading(false);
//     }
//   };

//   const openEditModal = (id) => {
//     setSelectedId(id);
//     setShowEdit(true);
//   };

//   const openRoleModal = (id) => {
//     setSelectedId(id);
//     setShowRoleModal(true);
//   };

//   const closeEditModal = () => {
//     setShowEdit(false);
//     setSelectedId(null);
//     loadUsers();
//   };

//   const closeRoleModal = () => {
//     setShowRoleModal(false);
//     setSelectedId(null);
//     loadUsers();
//   };
//   // const filteredUsers = users.filter(
//   //   (item) =>
//   //     item?.details?.full_name
//   //       ?.toLowerCase()
//   //       ?.includes(search.toLowerCase()) ||
//   //     item?.details?.organization_name
//   //       ?.toLowerCase()
//   //       ?.includes(search.toLowerCase())
//   // );

//   const filteredUsers = users.filter((item) => {
//     const searchText = search.toLowerCase();

//     return (
//       item?.details?.full_name?.toLowerCase()?.includes(searchText) ||
//       item?.details?.organization_name?.toLowerCase()?.includes(searchText) ||
//       item?.role_details?.[0]?.name?.toLowerCase()?.includes(searchText) ||
//       item?.details?.status?.toLowerCase()?.includes(searchText)
//     );
//   });

//   const indexOfLastUser = currentPage * usersPerPage;
//   const indexOfFirstUser = indexOfLastUser - usersPerPage;

//   const currentUsers = filteredUsers.slice(
//     indexOfFirstUser,
//     indexOfLastUser
//   );

//   const totalPages = Math.ceil(filteredUsers.length / usersPerPage);
//   useEffect(() => {
//     loadUsers();
//   }, []);

//   return (
//     <Layout title="User Management">
//       <div className="casestable mangelstPrent">
//         {loading ? (
//           <p>Loading users...</p>
//         ) :
//           <>
//             <div className="d-flex justify-content-end">
//               <div className="caseflter mb-3">
//                 <div className="filtersrch">
//                   <input
//                     type="text"
//                     placeholder="Search"
//                     value={search}
//                     onChange={(e) => {
//                       setSearch(e.target.value);
//                       setCurrentPage(1);
//                     }}
//                   />
//                   <input type="submit" value="" />
//                 </div>
//                 {/* <CustomSelect
//                 placeholder="Sort By"
//                 options={[
//                   { value: "1", label: "Option 1" },
//                   { value: "2", label: "Option 2" },
//                 ]}
//               /> */}
//               </div>
//             </div>
//             {currentUsers.length > 0 ?
//               <>
//                 {currentUsers.map((user) => (
//                   <ManagementItem
//                     key={user.id}
//                     user={user}
//                     onEdit={openEditModal}
//                     onRoleChange={openRoleModal}
//                   />
//                 ))}
//                 {totalPages > 1 && (
//                   <div className="pagination-wrapper">
//                     <button
//                       className="px-2 py-1"
//                       disabled={currentPage === 1}
//                       onClick={() => setCurrentPage((prev) => prev - 1)}
//                     >
//                       Previous
//                     </button>

//                     {[...Array(totalPages)].map((_, index) => (
//                       <button
//                         key={index + 1}
//                         className={currentPage === index + 1 ? "active" : ""}
//                         onClick={() => setCurrentPage(index + 1)}
//                       >
//                         {index + 1}
//                       </button>
//                     ))}

//                     <button
//                       className="px-2 py-1"
//                       disabled={currentPage === totalPages}
//                       onClick={() => setCurrentPage((prev) => prev + 1)}
//                     >
//                       Next
//                     </button>
//                   </div>
//                 )}
//               </>
//               : (
//                 <p>No users found</p>
//               )}
//           </>
//         }
//       </div>

//       <EditUserModal show={showEdit} onClose={closeEditModal} userId={selectedId} />
//       <ChangeRoleModal show={showRoleModal} onClose={closeRoleModal} userId={selectedId} />
//     </Layout>
//   );
// }

// import React, { useEffect, useState, useRef, useCallback } from "react";
// import { getUsers } from "@/services/userService";
// import { toast } from "react-toastify";
// import Layout from "../../Layout";
// import EditUserModal from "../../components/admin/user-management/EditUserModal";
// import ChangeRoleModal from "../../components/admin/user-management/ChangeRoleModal";
// import { assetPath } from "../../utils/assetPath";
// import { useProfile } from "@/context/ProfileContext";

// function ManagementItem({ user, onEdit, onRoleChange }) {
//   const { profile } = useProfile();
//   const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
//   const initials = user.details?.full_name
//     ? user.details.full_name
//       .split(" ")
//       .map((n) => n[0])
//       .join("")
//       .toUpperCase()
//     : "NA";

//   return (
//     <div className="managementlist">
//       <div className="media">
//         <div className="mnageuser">{initials}</div>
//         <div className="media-object">

//           <h3>{user.details?.full_name || "Unknown User"}</h3>
//           <span className="d-block">{user.details?.organization_name || "N/A"}</span>
//           <span
//             className={`mng-badge d-inline-flex d-sm-none ${user.role_details?.[0]?.name === "Analyst"
//               ? "role-bg"
//               : user.role_details?.[0]?.name === "Admin"
//                 ? "role-bga"
//                 : user.role_details?.[0]?.name?.trim().toLowerCase() === "paralegal"
//                   ? "role-bgp"
//                   : ""
//             }`}
//           >
//             {user.role_details?.[0]?.name || "Unknown Role"}
//           </span>
//         </div>
//       </div>

//       <div className="manageactin">
//         <div className="d-none d-sm-inline-flex gap-2 align-items-center">
//           <span>Role :</span>
//           <span
//             className={`mng-badge ${user.role_details?.[0]?.name === "Analyst"
//                 ? "role-bg"
//                 : user.role_details?.[0]?.name === "Admin"
//                   ? "role-bga"
//                   : user.role_details?.[0]?.name?.trim().toLowerCase() === "paralegal"
//                     ? "role-bgp"
//                     : ""
//               }`}
//           >
//             {user.role_details?.[0]?.name || "Unknown Role"}
//           </span>
//         </div>
//         <span
//           className={
//             user.details?.status === "available" ||
//               user.details?.status === "active"
//               ? "actvetxt"
//               : user.details?.status === "busy"
//                 ? "oflnetxt"
//                 : "oflnetxt"
//           }
//         >
//           <span>
//             {(user.details?.status || "unknown")
//             .charAt(0)
//             .toUpperCase() +
//             (user.details?.status || "unknown").slice(1).toLowerCase()}
//           </span>
//         </span>

//         {profile?.roles?.includes(5) && (
//           <div className="actindted">
//             <div className="dropdown">
//               <button
//                 className="dropdown-toggle"
//                 type="button"
//                 data-bs-toggle="dropdown"
//               >
//                 <img src={assetPath("/assets/images/dtedbig.png")} alt="" />
//               </button>

//               <ul className="dropdown-menu">
//                 <li style={{ cursor: "pointer" }}>
//                   <a onClick={() => onEdit(user.id)}>
//                     <i>
//                       <img src={assetPath("/assets/images/action_icn2.png")} alt="" />
//                     </i>
//                     Edit User
//                   </a>
//                 </li>

//                 <li style={{ cursor: "pointer" }}>
//                   <a onClick={() => onRoleChange(user.id)}>
//                     <i>
//                       <img src={assetPath("/assets/images/userrle.png")} alt="" />
//                     </i>
//                     Change Role
//                   </a>
//                 </li>
//               </ul>
//             </div>
//           </div>
//         )}
//       </div>
//     </div>
//   );
// }

// export default function UserManagement() {
//   const [users, setUsers] = useState([]);
//   const [loading, setLoading] = useState(true); // initial load
//   const [loadingMore, setLoadingMore] = useState(false); // subsequent page loads
//   const [showEdit, setShowEdit] = useState(false);
//   const [selectedId, setSelectedId] = useState(null);
//   const [showRoleModal, setShowRoleModal] = useState(false);
//   const [search, setSearch] = useState("");

//   // ---- Server-side pagination state ----
//   const LIMIT = 20;
//   const [page, setPage] = useState(1);
//   const [totalPages, setTotalPages] = useState(1);

//   const loaderRef = useRef(null);
//   const scrollContainerRef = useRef(null);

//   const loadUsers = async (pageNum = 1, append = false) => {
//     try {
//       append ? setLoadingMore(true) : setLoading(true);

//       const { data } = await getUsers(pageNum, LIMIT);

//       setUsers((prev) =>
//         append ? [...prev, ...(data?.results || [])] : data?.results || []
//       );
//       setTotalPages(data?.total_pages || 1);
//       setPage(data?.page || pageNum);
//     } catch (err) {
//       toast.error("Failed to load users");
//     } finally {
//       append ? setLoadingMore(false) : setLoading(false);
//     }
//   };

//   const openEditModal = (id) => {
//     setSelectedId(id);
//     setShowEdit(true);
//   };

//   const openRoleModal = (id) => {
//     setSelectedId(id);
//     setShowRoleModal(true);
//   };

//   const closeEditModal = () => {
//     setShowEdit(false);
//     setSelectedId(null);
//     loadUsers(1, false);
//   };

//   const closeRoleModal = () => {
//     setShowRoleModal(false);
//     setSelectedId(null);
//     loadUsers(1, false);
//   };

//   // Filters whatever pages have been loaded so far.
//   // NOTE: this only searches users already fetched into memory — it won't
//   // reach rows on pages you haven't scrolled to yet. For full-dataset
//   // search, ask the backend to accept a `search` query param.
//   const filteredUsers = users.filter((item) => {
//     const searchText = search.toLowerCase();

//     return (
//       item?.details?.full_name?.toLowerCase()?.includes(searchText) ||
//       item?.details?.organization_name?.toLowerCase()?.includes(searchText) ||
//       item?.role_details?.[0]?.name?.toLowerCase()?.includes(searchText) ||
//       item?.details?.status?.toLowerCase()?.includes(searchText)
//     );
//   });

//   const hasMore = page < totalPages;

//   useEffect(() => {
//     loadUsers(1, false);
//   }, []);

//   const loadMore = useCallback(() => {
//     if (loadingMore || !hasMore) return;
//     loadUsers(page + 1, true);
//   }, [loadingMore, hasMore, page]);

//   // Reveal more rows when the sentinel scrolls into view
//   const handleObserver = useCallback(
//     (entries) => {
//       const target = entries[0];
//       if (target.isIntersecting) {
//         loadMore();
//       }
//     },
//     [loadMore]
//   );

//   useEffect(() => {
//     const option = {
//       root: scrollContainerRef.current || null,
//       rootMargin: "100px",
//       threshold: 0,
//     };
//     const observer = new IntersectionObserver(handleObserver, option);
//     const currentLoader = loaderRef.current;
//     if (currentLoader) observer.observe(currentLoader);

//     return () => {
//       if (currentLoader) observer.unobserve(currentLoader);
//     };
//   }, [handleObserver]);

//   return (
//     <Layout title="User Management">
//       <div
//         className="casestable mangelstPrent"
//         ref={scrollContainerRef}
//         style={{ maxHeight: "75vh", overflowY: "auto" }}
//       >
//         {loading ? (
//           <p>Loading users...</p>
//         ) : (
//           <>
//             <div className="d-flex justify-content-end">
//               <div className="caseflter mb-3">
//                 <div className="filtersrch">
//                   <input
//                     type="text"
//                     placeholder="Search"
//                     value={search}
//                     onChange={(e) => {
//                       setSearch(e.target.value);
//                     }}
//                   />
//                   <input type="submit" value="" />
//                 </div>
//               </div>
//             </div>

//             {filteredUsers.length > 0 ? (
//               <>
//                 {filteredUsers.map((user) => (
//                   <ManagementItem
//                     key={user.id}
//                     user={user}
//                     onEdit={openEditModal}
//                     onRoleChange={openRoleModal}
//                   />
//                 ))}

//                 {hasMore && !search && (
//                   <div ref={loaderRef} className="text-center py-3">
//                     <span>{loadingMore ? "Loading more..." : ""}</span>
//                   </div>
//                 )}
//               </>
//             ) : (
//               <p>No users found</p>
//             )}
//           </>
//         )}
//       </div>

//       <EditUserModal show={showEdit} onClose={closeEditModal} userId={selectedId} />
//       <ChangeRoleModal show={showRoleModal} onClose={closeRoleModal} userId={selectedId} />
//     </Layout>
//   );
// }

import React, { useEffect, useState, useRef, useCallback } from "react";
import { getUsers } from "@/services/userService";
import { toast } from "react-toastify";
import Layout from "../../Layout";
import EditUserModal from "../../components/admin/user-management/EditUserModal";
import ChangeRoleModal from "../../components/admin/user-management/ChangeRoleModal";
import { assetPath } from "../../utils/assetPath";
import { useProfile } from "@/context/ProfileContext";
import Link from "next/link";

const PAGE_SIZE = 20;

function ManagementItem({ user, onEdit, onRoleChange }) {
  const { profile } = useProfile();
  const initials = user.details?.full_name
    ? user.details.full_name
        .split(" ")
        .map((n) => n[0])
        .join("")
        .toUpperCase()
    : "NA";

  const roleName = user.role_details?.[0]?.name ?? "Unknown Role";
  const roleBadgeClass =
    roleName === "Analyst"
      ? "role-bg"
      : roleName === "Admin"
        ? "role-bga"
        : roleName.trim().toLowerCase() === "paralegal"
          ? "role-bgp"
          : "";

  const status = user.details?.status ?? "unknown";
  const statusClass =
    status === "available" || status === "active" ? "actvetxt" : "oflnetxt";

  return (
    <div className="managementlist">
      <div className="media">
        <div className="mnageuser">{initials}</div>
        <div className="media-object">
          <h3>{user.details?.full_name || "Unknown User"}</h3>
          <span className="d-block">
            {user.details?.organization_name || "N/A"}
          </span>
          <span
            className={`mng-badge d-inline-flex d-sm-none ${roleBadgeClass}`}
          >
            {roleName}
          </span>
        </div>
      </div>

      <div className="manageactin">
        <div className="d-none d-sm-inline-flex gap-2 align-items-center">
          <span>Role :</span>
          <span className={`mng-badge ${roleBadgeClass}`}>{roleName}</span>
        </div>

        <span className={statusClass}>
          {status.charAt(0).toUpperCase() + status.slice(1).toLowerCase()}
        </span>

        {profile?.roles?.includes(5) && (
          <div className="actindted">
            <div className="dropdown">
              <button
                className="dropdown-toggle"
                type="button"
                data-bs-toggle="dropdown"
              >
                <img src={assetPath("/assets/images/dtedbig.png")} alt="" />
              </button>
              <ul className="dropdown-menu">
                <li style={{ cursor: "pointer" }}>
                  <a onClick={() => onEdit(user.id)}>
                    <i>
                      <img
                        src={assetPath("/assets/images/action_icn2.png")}
                        alt=""
                      />
                    </i>
                    Edit User
                  </a>
                </li>
                <li style={{ cursor: "pointer" }}>
                  <a onClick={() => onRoleChange(user.id)}>
                    <i>
                      <img
                        src={assetPath("/assets/images/userrle.png")}
                        alt=""
                      />
                    </i>
                    Change Role
                  </a>
                </li>
              </ul>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default function UserManagement() {
  const [allUsers, setAllUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showEdit, setShowEdit] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [showRoleModal, setShowRoleModal] = useState(false);
  const [search, setSearch] = useState("");
  const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);

  const loaderRef = useRef(null);
  const scrollContainerRef = useRef(null);

  const loadUsers = async () => {
    try {
      setLoading(true);
      const { data } = await getUsers(); // single call, all users
      setAllUsers(data?.results ?? data ?? []);
    } catch {
      toast.error("Failed to load users");
    } finally {
      setLoading(false);
    }
  };

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

  const openEditModal = (id) => {
    setSelectedId(id);
    setShowEdit(true);
  };
  const openRoleModal = (id) => {
    setSelectedId(id);
    setShowRoleModal(true);
  };
  const closeEditModal = () => {
    setShowEdit(false);
    setSelectedId(null);
    loadUsers();
  };
  const closeRoleModal = () => {
    setShowRoleModal(false);
    setSelectedId(null);
    loadUsers();
  };

  const filteredUsers = allUsers.filter((item) => {
    const q = search.toLowerCase();
    return (
      item?.details?.full_name?.toLowerCase().includes(q) ||
      item?.details?.organization_name?.toLowerCase().includes(q) ||
      item?.role_details?.[0]?.name?.toLowerCase().includes(q) ||
      item?.details?.status?.toLowerCase().includes(q)
    );
  });

  // Reset visible window whenever the search term changes
  useEffect(() => {
    setVisibleCount(PAGE_SIZE);
  }, [search]);

  // Rows actually rendered = first `visibleCount` of the filtered set
  const visibleUsers = filteredUsers.slice(0, visibleCount);
  const hasMore = visibleCount < filteredUsers.length;

  const loadMore = useCallback(() => {
    if (!hasMore) return;
    setVisibleCount((c) => c + PAGE_SIZE);
  }, [hasMore]);

  const handleObserver = useCallback(
    ([entry]) => {
      if (entry.isIntersecting) loadMore();
    },
    [loadMore],
  );

  useEffect(() => {
    const observer = new IntersectionObserver(handleObserver, {
      root: scrollContainerRef.current ?? null,
      rootMargin: "100px",
      threshold: 0,
    });
    const el = loaderRef.current;
    if (el) observer.observe(el);
    return () => {
      if (el) observer.unobserve(el);
    };
  }, [handleObserver]);

  return (
    <Layout title="User Management">
      <div className="pagerlink">
        <ul>
          <li>
            <Link href="/dashboard">Dashboard</Link>
          </li>
          <li>User Management</li>
        </ul>
      </div>
      <div
        className="casestable mangelstPrent"
        ref={scrollContainerRef}
        style={{ maxHeight: "75vh", overflowY: "auto" }}
      >
        {loading ? (
          <p>Loading users...</p>
        ) : (
          <>
            <div className="d-flex justify-content-end">
              <div className="caseflter mb-3">
                <div className="filtersrch">
                  <input
                    type="text"
                    placeholder="Search"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                  />
                  <input type="submit" value="" />
                </div>
              </div>
            </div>

            {visibleUsers.length > 0 ? (
              <>
                {visibleUsers.map((user) => (
                  <ManagementItem
                    key={user.id}
                    user={user}
                    onEdit={openEditModal}
                    onRoleChange={openRoleModal}
                  />
                ))}

                {/* Sentinel — always mounted so the observer keeps watching */}
                <div ref={loaderRef} className="text-center py-3">
                  {hasMore && <span>Loading more…</span>}
                </div>
              </>
            ) : (
              <p>No users found</p>
            )}
          </>
        )}
      </div>

      <EditUserModal
        show={showEdit}
        onClose={closeEditModal}
        userId={selectedId}
      />
      <ChangeRoleModal
        show={showRoleModal}
        onClose={closeRoleModal}
        userId={selectedId}
      />
    </Layout>
  );
}
