interface PaginationProps {
  pagination: {
    total: number;
    page: number;
    per_page: number;
    total_pages: number;
  } | null;
  onPageChange: (page: number) => void;
  onPerPageChange?: (perPage: number) => void;
}

export default function Pagination({
  pagination,
  onPageChange,
  onPerPageChange,
}: PaginationProps) {
  if (!pagination || pagination.total_pages <= 1) return null;

  const { page, total_pages, total } = pagination;

  const getPages = () => {
    const pages: (number | string)[] = [];
    const delta = 2;
    for (let i = 1; i <= total_pages; i++) {
      if (
        i === 1 ||
        i === total_pages ||
        (i >= page - delta && i <= page + delta)
      ) {
        pages.push(i);
      } else if (pages[pages.length - 1] !== "...") {
        pages.push("...");
      }
    }
    return pages;
  };

  return (
    <div className="admin-pagination">
      <div className="admin-pagination-info">{total} záznamů</div>
      <div className="admin-pagination-controls">
        <button
          disabled={page <= 1}
          onClick={() => onPageChange(page - 1)}
          className="admin-pagination-page"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
          >
            <path d="M15 18l-6-6 6-6" />
          </svg>
        </button>
        {getPages().map((p, i) =>
          typeof p === "string" ? (
            <span key={`dots-${i}`} className="admin-pagination-ellipsis">
              ...
            </span>
          ) : (
            <button
              key={p}
              onClick={() => onPageChange(p)}
              className={`admin-pagination-page ${p === page ? "active" : ""}`}
            >
              {p}
            </button>
          ),
        )}
        <button
          disabled={page >= total_pages}
          onClick={() => onPageChange(page + 1)}
          className="admin-pagination-page"
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
          >
            <path d="M9 18l6-6-6-6" />
          </svg>
        </button>
      </div>
      {onPerPageChange && (
        <select
          value={pagination.per_page}
          onChange={(e) => onPerPageChange(Number(e.target.value))}
          className="admin-pagination-select"
        >
          {[10, 25, 50, 100].map((n) => (
            <option key={n} value={n}>
              {n} / stránka
            </option>
          ))}
        </select>
      )}
    </div>
  );
}
