'use client';

import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from './button';

type GlobalPaginationProps = {
  page: number;
  total: number;
  pageSize: number;
  onChange: (page: number) => void;
};

const getPages = (current: number, total: number) => {
  const pages: (number | 'dots')[] = [];

  if (total <= 7) {
    return Array.from({ length: total }, (_, i) => i + 1);
  }

  pages.push(1);

  if (current > 4) {
    pages.push('dots');
  }

  const start = Math.max(2, current - 1);
  const end = Math.min(total - 1, current + 1);

  for (let i = start; i <= end; i++) {
    pages.push(i);
  }

  if (current < total - 3) {
    pages.push('dots');
  }

  pages.push(total);

  return pages;
};

export const GlobalPagination = ({
  page,
  total,
  pageSize,
  onChange,
}: GlobalPaginationProps) => {
  const totalPages = Math.ceil(total / pageSize);
  if (totalPages <= 1) return null;

  const pages = getPages(page, totalPages);

  return (
    <div className="flex items-center justify-center gap-2">
      <Button
        variant={'outline'}
        onClick={() => page > 1 && onChange(page - 1)}
        disabled={page === 1}
        className="flex items-center justify-center w-10 cursor-pointer h-10 rounded-lg transition-all duration-200 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent"
      >
        <ChevronLeft className="!w-6 !h-6 text-gray-600" />
      </Button>

      {/* Page Numbers */}
      <div className="flex items-center gap-1">
        {pages.map((p, i) => (
          <div key={i}>
            {p === 'dots' ? (
              <span className="flex items-center justify-center w-9 h-9 text-gray-400 font-medium">
                ···
              </span>
            ) : (
              <Button
                variant={'outline'}
                onClick={() => onChange(p)}
                className={`
                  flex items-center justify-center w-10 h-10 px-3 rounded-lg font-medium transition-all duration-200
                  ${
                    p === page
                      ? 'bg-blue-600 text-white shadow-md shadow-blue-200 scale-105'
                      : 'text-gray-700 hover:bg-gray-100 hover:scale-105'
                  }
                `}
              >
                {p}
              </Button>
            )}
          </div>
        ))}
      </div>

      <Button
        onClick={() => page < totalPages && onChange(page + 1)}
        disabled={page === totalPages}
        variant={'outline'}
        className="flex items-center justify-center w-10 cursor-pointer h-10 rounded-lg transition-all duration-200 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent"
      >
        <ChevronRight className="!w-6 !h-6 text-gray-600" />
      </Button>
    </div>
  );
};
