"use client";

import { useEffect, useState } from "react";

interface PaginationProps {
  currentPage: number;
  lastPage: number;
  onPageChange: (page: number) => void;
}

export default function Pagination({
  currentPage,
  lastPage,
  onPageChange,
}: PaginationProps) {
  const [visiblePages, setVisiblePages] = useState<number[]>([]);
  // const [atBottom, setAtBottom] = useState<boolean>(false);
  // const bottomPaginationRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const pages: number[] = [];
    const range = 1;
    const start = Math.max(currentPage - range, 1);
    const end = Math.min(currentPage + range, lastPage);

    for (let i = start; i <= end; i++) {
      pages.push(i);
    }

    setVisiblePages(pages);
  }, [currentPage, lastPage]);

  // useEffect(() => {
  //   const observer = new IntersectionObserver(
  //     ([entry]) => {
  //       setAtBottom(entry.isIntersecting);
  //     },
  //     {
  //       root: null, // viewport
  //       threshold: 1.0,
  //     }
  //   );

  //   if (bottomPaginationRef.current) {
  //     observer.observe(bottomPaginationRef.current);
  //   }

  //   return () => {
  //     if (bottomPaginationRef.current) {
  //       observer.unobserve(bottomPaginationRef.current);
  //     }
  //   };
  // }, []);

  const showPreviousEllipsis = visiblePages[0] > 2;
  const showNextEllipsis = visiblePages[visiblePages.length - 1] < lastPage - 1;

  const handleExpandLeft = () => {
    const first = visiblePages[0];
    const newPages: number[] = [];
    for (let i = Math.max(first - 2, 1); i < first; i++) {
      newPages.push(i);
    }
    setVisiblePages((curr) => [...newPages, ...curr]);
  };

  const handleExpandRight = () => {
    const last = visiblePages[visiblePages.length - 1];
    const newPages: number[] = [];
    for (let i = last + 1; i <= Math.min(last + 2, lastPage); i++) {
      newPages.push(i);
    }
    setVisiblePages((curr) => [...curr, ...newPages]);
  };

  return (
    <>
      {/* <div ref={bottomPaginationRef} className="h-1" /> */}
      <div className="flex justify-center items-center gap-2 p-5 flex-wrap z-100 bg-white w-full drop-shadow-2xl"
        style={{
          position: "fixed",
          left: '50%',
          transform: 'translateX(-50%)',
          // bottom: atBottom ? '200px' : '62px',
          bottom: '62px',
          transition: "all 0.7s ease",
        }}
      >
        <button
          className="px-3 py-1 rounded bg-gray-200 text-gray-800 cursor-pointer disabled:cursor-default disabled:opacity-50"
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage <= 1}
        >
          Previous
        </button>

        {visiblePages[0] > 1 && (
          <>
            <button
              onClick={() => onPageChange(1)}
              className={`px-3 py-1 rounded cursor-pointer disabled:cursor-default ${currentPage === 1
                ? "bg-pink-500 text-white font-semibold"
                : "bg-gray-100 text-gray-800 hover:bg-gray-300"
                }`}
            >
              1
            </button>
            {showPreviousEllipsis && (
              <span
                onClick={handleExpandLeft}
                className="px-2 text-gray-500 cursor-pointer select-none"
              >
                …
              </span>
            )}
          </>
        )}

        {visiblePages.map((page) => (
          <button
            key={page}
            onClick={() => onPageChange(page)}
            className={`px-3 py-1 rounded cursor-pointer disabled:cursor-default ${currentPage === page
              ? "bg-pink-500 text-white font-semibold"
              : "bg-gray-100 text-gray-800 hover:bg-gray-300"
              }`}
          >
            {page}
          </button>
        ))}

        {visiblePages[visiblePages.length - 1] < lastPage && (
          <>
            {showNextEllipsis && (
              <span
                onClick={handleExpandRight}
                className="px-2 text-gray-500 cursor-pointer select-none"
              >
                …
              </span>
            )}
            <button
              onClick={() => onPageChange(lastPage)}
              className={`px-3 py-1 rounded cursor-pointer disabled:cursor-default ${currentPage === lastPage
                ? "bg-pink-500 text-white font-semibold"
                : "bg-gray-100 text-gray-800 hover:bg-gray-300"
                }`}
            >
              {lastPage}
            </button>
          </>
        )}

        <button
          className="px-3 py-1 rounded bg-gray-200 text-gray-800 cursor-pointer disabled:cursor-default disabled:opacity-50"
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage >= lastPage}
        >
          Next
        </button>
      </div>
    </>
  );
}
