import React from 'react';
import { ChevronRightIcon, ChevronLeftIcon } from '@heroicons/react/24/outline';
import { formatNumber } from '../../lib/utils';

interface Props {
  page: number;
  total: number;
  limit: number;
  onPageChange: (page: number) => void;
}

export default function Pagination({ page, total, limit, onPageChange }: Props) {
  const totalPages = Math.ceil(total / limit);
  if (totalPages <= 1) return null;

  const from = (page - 1) * limit + 1;
  const to   = Math.min(page * limit, total);

  const pages: (number | '...')[] = [];
  if (totalPages <= 7) {
    for (let i = 1; i <= totalPages; i++) pages.push(i);
  } else {
    pages.push(1);
    if (page > 3) pages.push('...');
    for (let i = Math.max(2, page - 1); i <= Math.min(totalPages - 1, page + 1); i++) pages.push(i);
    if (page < totalPages - 2) pages.push('...');
    pages.push(totalPages);
  }

  return (
    <div className="pagination" data-tour="page-pagination">
      <span style={{ fontSize: 12.5, color: 'var(--text-3)' }}>
        نمایش {formatNumber(from)}–{formatNumber(to)} از {formatNumber(total)} مورد
      </span>

      <div className="page-btns">
        <button
          onClick={() => onPageChange(page - 1)}
          disabled={page === 1}
        >
          <ChevronRightIcon style={{ width: 16, height: 16 }} />
        </button>

        {pages.map((p, i) =>
          p === '...' ? (
            <span key={`d-${i}`} style={{ minWidth: 36, height: 36, display: 'grid', placeItems: 'center', fontSize: 13, color: 'var(--text-3)' }}>
              …
            </span>
          ) : (
            <button
              key={p}
              onClick={() => onPageChange(p as number)}
              className={p === page ? 'on' : ''}
            >
              {formatNumber(p as number)}
            </button>
          )
        )}

        <button
          onClick={() => onPageChange(page + 1)}
          disabled={page === totalPages}
        >
          <ChevronLeftIcon style={{ width: 16, height: 16 }} />
        </button>
      </div>
    </div>
  );
}
