"use client";
import Link from "next/link";
import { useState, useEffect } from "react";
import styles from "./Pagination.module.css";

type PaginationProps = {
  currentPage: number;
  totalPages: number;
};

export default function Pagination({
  currentPage,
  totalPages,
}: PaginationProps) {
  const visiblePageCount = 4;
  const [groupStart, setGroupStart] = useState(1);

  // Update group when currentPage changes (like when URL param changes)
  useEffect(() => {
    const newStart = Math.max(2, currentPage - 1);
    setGroupStart(newStart);
  }, [currentPage]);

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

  const pages: (number | "prevDots" | "nextDots")[] = [1];

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

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

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

  pages.push(totalPages);

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

  return (
    <div className={styles.wrapper}>
      {currentPage > 1 && (
        <Link href={`?page=${currentPage - 1}`} className={styles.button}>
          « Prev
        </Link>
      )}

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

        if (page === "nextDots") {
          return (
            <button
              key={`dots-next-${index}`}
              className={styles.dots}
              onClick={() => handleDotsClick("next")}
            >
              ...
            </button>
          );
        }

        return (
          <Link
            key={`page-${page}`}
            href={`?page=${page}`}
            className={`${styles.button} ${
              currentPage === page ? styles.active : ""
            }`}
          >
            {page}
          </Link>
        );
      })}

      {currentPage < totalPages && (
        <Link href={`?page=${currentPage + 1}`} className={styles.button}>
          Next »
        </Link>
      )}
    </div>
  );
}
