"use client";

import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import type { PaginationItem } from "@/components/ui/data-table/data-table-types";
import { formatNumber } from "@/lib/number-utils";

type DataTablePaginationProps = {
  page: number;
  pageCount: number;
  onPrevious: () => void;
  onNext: () => void;
  onSelectPage: (pageIndex: number) => void;
  /** When true, show a disabled empty-state pager with "0". */
  isEmpty?: boolean;
};

function buildVisiblePages(page: number, pageCount: number): PaginationItem[] {
  if (pageCount <= 7) {
    return Array.from({ length: pageCount }, (_, index) => index + 1);
  }

  const currentPage = page + 1;

  if (currentPage <= 3 || currentPage >= pageCount - 2) {
    return [1, 2, 3, "...", pageCount - 2, pageCount - 1, pageCount];
  }

  return [
    1,
    "...",
    currentPage - 1,
    currentPage,
    currentPage + 1,
    "...",
    pageCount,
  ];
}

export function DataTablePagination({
  page,
  pageCount,
  onPrevious,
  onNext,
  onSelectPage,
  isEmpty = false,
}: DataTablePaginationProps) {
  const { language } = useAppLanguage();
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const visiblePages = buildVisiblePages(page, pageCount);
  const canGoPrevious = !isEmpty && page > 0;
  const canGoNext = !isEmpty && page + 1 < pageCount;

  const arrowButtonSx = {
    height: 36,
    px: 1.5,
    borderRadius: "8px",
    border: `1px solid ${isDark ? alpha("#ffffff", 0.14) : "#d5d7da"}`,
    boxShadow: isDark ? "none" : "0px 1px 2px rgba(10, 13, 18, 0.05)",
    display: "inline-flex",
    alignItems: "center",
    gap: 0.5,
    color: isDark ? alpha("#ffffff", 0.78) : "#414651",
    bgcolor: isDark ? alpha("#ffffff", 0.04) : "#ffffff",
    "&:hover": {
      bgcolor: isDark ? alpha("#ffffff", 0.08) : "#fafafa",
    },
    "&.Mui-disabled": {
      opacity: 1,
      color: isDark ? alpha("#ffffff", 0.28) : "#d5d7da",
    },
  };

  return (
    <Box
      sx={{
        borderTop: `1px solid ${isDark ? alpha("#ffffff", 0.1) : "#f5f5f5"}`,
        backgroundColor: isDark ? "#101828" : "#ffffff",
        px: 3,
        pt: 1.5,
        pb: 2,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 1.5,
        flexWrap: { xs: "wrap", lg: "nowrap" },
        flexShrink: 0,
      }}
    >
      <Box sx={{ flex: 1, minWidth: 0 }}>
        <ButtonBase
          onClick={canGoPrevious ? onPrevious : undefined}
          disabled={!canGoPrevious}
          sx={arrowButtonSx}
        >
          <ChevronLeftIcon sx={{ fontSize: 18 }} />
          <Typography sx={{ fontSize: 12, fontWeight: 500 }}>
            Previous
          </Typography>
        </ButtonBase>
      </Box>

      <Box sx={{ display: "flex", alignItems: "center", gap: 0.25 }}>
        {isEmpty ? (
          <Box
            sx={{
              width: 40,
              height: 40,
              borderRadius: "8px",
              display: "grid",
              placeItems: "center",
              backgroundColor: isDark ? alpha("#ffffff", 0.1) : "#fafafa",
              color: isDark ? "#ffffff" : "#252b37",
              fontSize: 14,
              fontWeight: 500,
            }}
          >
            {formatNumber(0, language)}
          </Box>
        ) : (
          visiblePages.map((item, index) => {
            if (item === "...") {
              return (
                <Box
                  key={`ellipsis-${index}`}
                  sx={{
                    width: 40,
                    height: 40,
                    display: "grid",
                    placeItems: "center",
                    color: isDark ? alpha("#ffffff", 0.56) : "#717680",
                    fontSize: 14,
                    fontWeight: 500,
                  }}
                >
                  ...
                </Box>
              );
            }

            const active = item === page + 1;

            return (
              <ButtonBase
                key={item}
                onClick={() => onSelectPage(Number(item) - 1)}
                sx={{
                  width: 40,
                  height: 40,
                  borderRadius: "8px",
                  backgroundColor: active
                    ? isDark
                      ? alpha("#ffffff", 0.1)
                      : "#fafafa"
                    : "transparent",
                  color: active
                    ? isDark
                      ? "#ffffff"
                      : "#252b37"
                    : isDark
                      ? alpha("#ffffff", 0.58)
                      : "#717680",
                  fontSize: 14,
                  fontWeight: 500,
                  "&:hover": {
                    backgroundColor: isDark
                      ? alpha("#ffffff", 0.08)
                      : "#fafafa",
                  },
                }}
              >
                {formatNumber(item, language)}
              </ButtonBase>
            );
          })
        )}
      </Box>

      <Box
        sx={{
          flex: 1,
          minWidth: 0,
          display: "flex",
          justifyContent: "flex-end",
        }}
      >
        <ButtonBase
          onClick={canGoNext ? onNext : undefined}
          disabled={!canGoNext}
          sx={arrowButtonSx}
        >
          <Typography sx={{ fontSize: 12, fontWeight: 500 }}>Next</Typography>
          <ChevronRightIcon sx={{ fontSize: 18 }} />
        </ButtonBase>
      </Box>
    </Box>
  );
}
