"use client";
import { useState, useEffect, useMemo } from "react";
import styles from "./Pagination.module.css";
import Button from "@/components/Base/Button/Button";

type PaginationProps = {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
};

export default function Pagination({
  currentPage,
  totalPages,
  onPageChange,
}: PaginationProps) {
  const visiblePageCount = 3;
  const maxGroupStart = Math.max(2, totalPages - visiblePageCount);

  const [groupStart, setGroupStart] = useState(Math.max(2, currentPage - 1));

  useEffect(() => {
    const newStart = Math.max(2, Math.min(currentPage - 1, maxGroupStart));
    setGroupStart(newStart);
  }, [currentPage, maxGroupStart]);

  const groupEnd = Math.min(groupStart + visiblePageCount - 1, totalPages - 1);

  const pages = useMemo<(number | "prevDots" | "nextDots")[]>(() => {
    const tempPages: (number | "prevDots" | "nextDots")[] = [1];

    if (groupStart > 2) tempPages.push("prevDots");

    for (let i = groupStart; i <= groupEnd; i++) {
      tempPages.push(i);
    }

    if (groupEnd < totalPages - 1) tempPages.push("nextDots");

    if (totalPages > 1) tempPages.push(totalPages);

    return tempPages;
  }, [groupStart, groupEnd, totalPages]);

  const handleDotsClick = (direction: "prev" | "next") => {
    setGroupStart((prev) => {
      if (direction === "prev") {
        return Math.max(2, prev - visiblePageCount);
      } else {
        return Math.min(maxGroupStart, prev + visiblePageCount);
      }
    });
  };

  return (
    <div className={styles.wrapper}>
      {currentPage > 1 && (
        <button
          onClick={() => onPageChange(currentPage - 1)}
          className={styles.button}
        >
          « Prev
        </button>
      )}

      {pages.map((page, index) => {
        if (page === "prevDots" || page === "nextDots") {
          return (
            <button
              key={`dots-${index}`}
              className={styles.dots}
              onClick={() =>
                handleDotsClick(page === "prevDots" ? "prev" : "next")
              }
            >
              ...
            </button>
          );
        }

        return (
          <Button
            key={`page-${page}`}
            variant="primary"
            size="sm"
            active={currentPage === page}
            onClick={() => onPageChange(page)}
          >
            {page}
          </Button>
        );
      })}

      {currentPage < totalPages && (
        <button
          onClick={() => onPageChange(currentPage + 1)}
          className={styles.button}
        >
          Next »
        </button>
      )}
    </div>
  );
}
