'use client';

import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

interface PaginationLabels {
  showing: string;
  to: string;
  of: string;
  perPage: string;
  previous: string;
  next: string;
}

interface PaginationControlsProps {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  labels: PaginationLabels;
  maxPageButtons?: number;
  alignment?: 'between' | 'right' | 'center';
  showSummary?: boolean;
  showPageSize?: boolean;
  loading?: boolean;
  className?: string;
  pageSize?: number;
  pageSizeOptions?: number[];
  onPageSizeChange?: (size: number) => void;
  showingFrom?: number;
  showingTo?: number;
  totalItems?: number;
}

function buildVisiblePages(
  currentPage: number,
  totalPages: number,
  maxPageButtons: number
): Array<number | 'ellipsis-left' | 'ellipsis-right'> {
  const safeMaxButtons = Math.max(3, maxPageButtons);

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

  const pages: Array<number | 'ellipsis-left' | 'ellipsis-right'> = [];
  const half = Math.floor(safeMaxButtons / 2);
  let start = Math.max(1, currentPage - half);
  let end = start + safeMaxButtons - 1;

  if (end > totalPages) {
    end = totalPages;
    start = Math.max(1, end - safeMaxButtons + 1);
  }

  if (start > 1) {
    pages.push(1);
    if (start > 2) pages.push('ellipsis-left');
  }

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

  if (end < totalPages) {
    if (end < totalPages - 1) pages.push('ellipsis-right');
    pages.push(totalPages);
  }

  return pages;
}

export default function PaginationControls({
  currentPage,
  totalPages,
  onPageChange,
  labels,
  maxPageButtons = 7,
  alignment = 'between',
  showSummary = true,
  showPageSize = true,
  loading = false,
  className = '',
  pageSize,
  pageSizeOptions = [10, 20, 50],
  onPageSizeChange,
  showingFrom,
  showingTo,
  totalItems,
}: PaginationControlsProps) {
  const safeTotalPages = Math.max(1, totalPages);
  const safeCurrentPage = Math.min(Math.max(1, currentPage), safeTotalPages);
  const pages = buildVisiblePages(safeCurrentPage, safeTotalPages, maxPageButtons);
  const showInfoBlock = showSummary || showPageSize;
  const desktopAlignmentClass =
    alignment === 'right'
      ? 'sm:justify-end'
      : alignment === 'center'
        ? 'sm:justify-center'
        : 'sm:justify-between';

  return (
    <div className={`flex flex-col items-center gap-3 border-t border-slate-100 px-4 py-3 sm:flex-row sm:items-center ${desktopAlignmentClass} ${className}`}>
      {showInfoBlock ? (
      <div className="flex w-full flex-wrap items-center justify-center gap-2 text-sm text-slate-600 sm:w-auto sm:justify-start">
        {showSummary && typeof showingFrom === 'number' && typeof showingTo === 'number' && typeof totalItems === 'number' ? (
          <>
            <span>{labels.showing}</span>
            <span className="font-medium">
              {showingFrom} {labels.to} {showingTo}
            </span>
            <span>
              {labels.of} {totalItems}
            </span>
          </>
        ) : null}

        {showPageSize && typeof pageSize === 'number' && onPageSizeChange ? (
          <Select value={String(pageSize)} onValueChange={(val) => onPageSizeChange(parseInt(val, 10))}>
            <SelectTrigger className="h-8 w-28">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {pageSizeOptions.map((size) => (
                <SelectItem key={size} value={String(size)}>
                  {size} / {labels.perPage}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        ) : null}
      </div>
      ) : null}

      <div className="flex w-full items-center justify-center gap-2 overflow-x-auto sm:w-auto sm:justify-end">
        <Button
          variant="outline"
          size="sm"
          disabled={safeCurrentPage <= 1 || loading}
          onClick={() => onPageChange(Math.max(1, safeCurrentPage - 1))}
          className="shrink-0 whitespace-nowrap"
        >
          <span className="sm:hidden">&lt;</span>
          <span className="hidden sm:inline">{labels.previous}</span>
        </Button>

        <div className="flex shrink-0 items-center gap-1">
          {pages.map((page, idx) =>
            typeof page === 'number' ? (
              <Button
                key={page}
                variant={safeCurrentPage === page ? 'default' : 'outline'}
                size="sm"
                disabled={loading}
                onClick={() => onPageChange(page)}
                className="min-w-9 shrink-0"
              >
                {page}
              </Button>
            ) : (
              <span key={`${page}-${idx}`} className="shrink-0 px-2 text-slate-500">
                ...
              </span>
            )
          )}
        </div>

        <Button
          variant="outline"
          size="sm"
          disabled={safeCurrentPage >= safeTotalPages || loading}
          onClick={() => onPageChange(Math.min(safeTotalPages, safeCurrentPage + 1))}
          className="shrink-0 whitespace-nowrap"
        >
          <span className="sm:hidden">&gt;</span>
          <span className="hidden sm:inline">{labels.next}</span>
        </Button>
      </div>
    </div>
  );
}
