"use client";

import { Pagination, PaginationItem, useMediaQuery, useTheme } from "@mui/material";
import { usePathname, useSearchParams } from "next/navigation";

function PaginationContent({ page, pageDetail, changePage, limit = 12 }) {
  const theme = useTheme();
  const isSmall = useMediaQuery(theme.breakpoints.down("sm"));
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const count = Math.ceil(pageDetail.totalRecords / limit);

  // href واقعی برای خزنده‌ها؛ کلیک کاربر همچنان SPA می‌ماند (preventDefault + onChange)
  const buildHref = (pageNum) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("page", String(pageNum));
    return `${pathname}?${params.toString()}`;
  };

  return (
    <Pagination
      count={count}
      page={page || 1}
      size={isSmall ? "small" : "medium"}
      onChange={changePage}
      color="primary"
      className={(!count || count < 2) && "!hidden"}
      renderItem={(item) => {
        const crawlable =
          item.page && item.page >= 1 && item.page <= count && !item.disabled;
        return (
          <PaginationItem
            {...item}
            {...(crawlable && {
              component: "a",
              href: buildHref(item.page),
              onClick: (event) => {
                event.preventDefault();
                item.onClick?.(event);
              },
            })}
          />
        );
      }}
      sx={{
        "& .MuiPaginationItem-root": {
          color: "#616161",
          fontSize: "16px",
          fontWeight: "500",
        },
        "& .MuiPaginationItem-root.Mui-selected": {
          color: "#F8F8FF",
        },
        "& .MuiSvgIcon-root": {
          rotate: "180deg !important",
        },
      }}
    />
  );
}

export default PaginationContent;
