"use client";

import type { Table } from "@tanstack/react-table";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useCallback, useEffect } from "react";
import { useSearchParams } from "react-router-dom";

interface Props<T> {
  table: Table<T>;
  totalPages?: number;
  namePage?: string;
  namePageSize?: string;
}

const RealPagination = <T,>({
  table,
  totalPages = 1,
  namePage,
  namePageSize,
}: Props<T>) => {
  const [searchParams, setSearchParams] = useSearchParams();

  const currentPage = table.getState().pagination.pageIndex + 1;

  const updateUrl = useCallback(
    (page: number, pageSize: number) => {
      const newParams = new URLSearchParams(searchParams);
      newParams.set(namePage ? namePage : "page", page.toString());
      newParams.set(
        namePageSize ? namePageSize : "pageSize",
        pageSize.toString(),
      );
      setSearchParams(newParams);
    },
    [searchParams, setSearchParams],
  );

  useEffect(() => {
    const urlPage = parseInt(searchParams.get("page") || "1", 10);
    const urlPageSize = parseInt(searchParams.get("pageSize") || "10", 10);

    if (urlPage - 1 !== table.getState().pagination.pageIndex) {
      table.setPageIndex(urlPage - 1);
    }
    if (urlPageSize !== table.getState().pagination.pageSize) {
      table.setPageSize(urlPageSize);
    }
  }, [searchParams, table]);

  const handlePrev = () => {
    if (currentPage > 1) {
      table.setPageIndex(currentPage - 2);
      updateUrl(currentPage - 1, table.getState().pagination.pageSize);
    }
  };

  const handleNext = () => {
    if (currentPage < totalPages) {
      table.setPageIndex(currentPage);
      updateUrl(currentPage + 1, table.getState().pagination.pageSize);
    }
  };

  const handlePageClick = (page: number) => {
    table.setPageIndex(page - 1);
    updateUrl(page, table.getState().pagination.pageSize);
  };

  return (
    <div className="flex justify-end gap-2 mt-4">
      {/* Previous Button */}
      <button
        disabled={currentPage === 1}
        onClick={handlePrev}
        className="p-2 rounded-lg border border-slate-600 text-slate-300 hover:bg-slate-700/50 
                   disabled:opacity-50 disabled:cursor-not-allowed transition-all hover:border-slate-500"
      >
        <ChevronLeft className="w-5 h-5" />
      </button>

      {/* Page Numbers */}
      {[...Array(totalPages)].map((_, i) => (
        <button
          key={i}
          onClick={() => handlePageClick(i + 1)}
          className={`px-4 py-2 rounded-lg border transition-all font-medium ${
            currentPage === i + 1
              ? "bg-gradient-to-r from-blue-600 to-cyan-600 border-blue-500 text-white shadow-lg shadow-cyan-500/50"
              : "border-slate-600 text-slate-300 hover:bg-slate-700/50 hover:border-slate-500"
          }`}
        >
          {i + 1}
        </button>
      ))}

      {/* Next Button */}
      <button
        disabled={currentPage === totalPages}
        onClick={handleNext}
        className="p-2 rounded-lg border border-slate-600 text-slate-300 hover:bg-slate-700/50 
                   disabled:opacity-50 disabled:cursor-not-allowed transition-all hover:border-slate-500"
      >
        <ChevronRight className="w-5 h-5" />
      </button>
    </div>
  );
};

export default RealPagination;
