"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
          variant="primary"
          size="md"
          onClick={() => onPageChange(currentPage - 1)}
        >
          « Prev
        </Button>
      )}

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

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

      {currentPage < totalPages && (
        <Button
          variant="primary"
          size="md"
          onClick={() => onPageChange(currentPage + 1)}
        >
          Next »
        </Button>
      )}
    </div>
  );
}
