import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';

export interface ListPaginationProps {
  currentPage: number;
  totalCount?: number;
  pageSize: number;
  hasMore?: boolean;
  itemLabel?: string;
  onPageChange: (page: number) => void;
  className?: string;
}

const ListPagination: React.FC<ListPaginationProps> = ({
  currentPage,
  totalCount = 0,
  pageSize,
  hasMore = false,
  itemLabel,
  onPageChange,
  className = '',
}) => {
  const { t } = useTranslation();
  const displayLabel = itemLabel ?? t('listPages.results');
  const totalPages = totalCount > 0 ? Math.max(1, Math.ceil(totalCount / pageSize)) : 0;
  const hasTotal = totalCount > 0;
  const start = (currentPage - 1) * pageSize + 1;
  const end = hasTotal
    ? Math.min(currentPage * pageSize, totalCount)
    : currentPage * pageSize;

  const [goToInput, setGoToInput] = useState('');

  const handleGoToSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const num = parseInt(goToInput.trim(), 10);
    if (!Number.isNaN(num) && num >= 1) {
      const target = hasTotal ? Math.min(num, totalPages) : num;
      onPageChange(target);
      setGoToInput('');
    }
  };

  const getPageNumbers = (): (number | 'ellipsis')[] => {
    if (totalPages <= 7) {
      return Array.from({ length: totalPages }, (_, i) => i + 1);
    }
    const pages: (number | 'ellipsis')[] = [];
    pages.push(1);
    if (currentPage > 3) pages.push('ellipsis');
    for (let p = Math.max(2, currentPage - 1); p <= Math.min(totalPages - 1, currentPage + 1); p++) {
      if (!pages.includes(p)) pages.push(p);
    }
    if (currentPage < totalPages - 2) pages.push('ellipsis');
    if (totalPages > 1) pages.push(totalPages);
    return pages;
  };

  const showPagination = hasMore || currentPage > 1 || (hasTotal && totalPages > 1);

  if (!showPagination) return null;

  return (
    <div className={`flex flex-wrap items-center justify-between gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700 ${className}`}>
      <div className="text-sm text-gray-700 dark:text-gray-300">
        {hasTotal
          ? t('pagination.showingToOf', { start, end, total: totalCount, label: displayLabel })
          : t('pagination.showingTo', { start, end, label: displayLabel })}
      </div>

      <div className="flex flex-wrap items-center gap-2">
        <button
          type="button"
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage <= 1}
          className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {t('pagination.previous')}
        </button>

        {hasTotal && totalPages > 1 && (
          <div className="flex items-center gap-1">
            {getPageNumbers().map((p, i) =>
              p === 'ellipsis' ? (
                <span key={`e-${i}`} className="px-2 text-gray-500 dark:text-gray-400">
                  …
                </span>
              ) : (
                <button
                  key={p}
                  type="button"
                  onClick={() => onPageChange(p)}
                  className={`min-w-[2rem] px-2 py-1 text-sm font-medium rounded-lg transition-colors ${
                    p === currentPage
                      ? 'bg-blue-600 text-white border border-blue-600'
                      : 'text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-600'
                  }`}
                >
                  {p}
                </button>
              )
            )}
          </div>
        )}

        <button
          type="button"
          onClick={() => onPageChange(currentPage + 1)}
          disabled={hasTotal ? currentPage >= totalPages : !hasMore}
          className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {t('pagination.next')}
        </button>

        <form onSubmit={handleGoToSubmit} className="flex items-center gap-1 ml-2">
          <span className="text-sm text-gray-600 dark:text-gray-400 whitespace-nowrap">{t('pagination.goTo')}</span>
          <input
            type="number"
            min={1}
            max={hasTotal ? totalPages : undefined}
            value={goToInput}
            onChange={(e) => setGoToInput(e.target.value)}
            placeholder={hasTotal ? `1-${totalPages}` : t('pagination.page')}
            className="w-14 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <button
            type="submit"
            className="px-2 py-1 text-sm font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            {t('pagination.go')}
          </button>
        </form>
      </div>
    </div>
  );
};

export default ListPagination;
