/**
 * Composant TrackListPagination
 * Pagination pour la liste de pistes avec contrôles de navigation
 */

import {
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
} from 'lucide-react';
import { cn } from '@/lib/utils';

export interface TrackListPaginationProps {
  currentPage: number;
  totalPages: number;
  totalItems: number;
  itemsPerPage: number;
  onPageChange: (page: number) => void;
  className?: string;
  showPageNumbers?: boolean;
  maxVisiblePages?: number;
  showItemsInfo?: boolean;
  disabled?: boolean;
}

export function TrackListPagination({
  currentPage,
  totalPages,
  totalItems,
  itemsPerPage,
  onPageChange,
  className,
  showPageNumbers = true,
  maxVisiblePages = 5,
  showItemsInfo = true,
  disabled = false,
}: TrackListPaginationProps) {
  const canGoPrevious = currentPage > 1 && !disabled;
  const canGoNext = currentPage < totalPages && !disabled;
  const canGoFirst = currentPage > 1 && !disabled;
  const canGoLast = currentPage < totalPages && !disabled;

  const handleFirstPage = () => {
    if (canGoFirst) {
      onPageChange(1);
    }
  };

  const handlePreviousPage = () => {
    if (canGoPrevious) {
      onPageChange(currentPage - 1);
    }
  };

  const handleNextPage = () => {
    if (canGoNext) {
      onPageChange(currentPage + 1);
    }
  };

  const handleLastPage = () => {
    if (canGoLast) {
      onPageChange(totalPages);
    }
  };

  const handlePageClick = (page: number) => {
    if (!disabled && page !== currentPage && page >= 1 && page <= totalPages) {
      onPageChange(page);
    }
  };

  // Calculer les numéros de page à afficher
  const getVisiblePages = (): number[] => {
    if (totalPages <= maxVisiblePages) {
      return Array.from({ length: totalPages }, (_, i) => i + 1);
    }

    const half = Math.floor(maxVisiblePages / 2);
    let start = Math.max(1, currentPage - half);
    const end = Math.min(totalPages, start + maxVisiblePages - 1);

    // Ajuster le début si on est proche de la fin
    if (end - start < maxVisiblePages - 1) {
      start = Math.max(1, end - maxVisiblePages + 1);
    }

    return Array.from({ length: end - start + 1 }, (_, i) => start + i);
  };

  const visiblePages = getVisiblePages();
  const startItem = totalItems > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0;
  const endItem = Math.min(currentPage * itemsPerPage, totalItems);

  if (totalPages <= 1 && !showItemsInfo) {
    return null;
  }

  return (
    <div
      className={cn(
        'flex flex-col sm:flex-row items-center justify-between gap-4',
        'px-4 py-3 border-t border-gray-200 dark:border-gray-700',
        className,
      )}
      role="navigation"
      aria-label="Pagination de la liste de pistes"
    >
      {/* Informations sur les items */}
      {showItemsInfo && (
        <div className="text-sm text-gray-600 dark:text-gray-400">
          Affichage de{' '}
          <span className="font-medium text-gray-900 dark:text-white">
            {startItem}
          </span>{' '}
          à{' '}
          <span className="font-medium text-gray-900 dark:text-white">
            {endItem}
          </span>{' '}
          sur{' '}
          <span className="font-medium text-gray-900 dark:text-white">
            {totalItems}
          </span>{' '}
          pistes
        </div>
      )}

      {/* Contrôles de pagination */}
      <div className="flex items-center gap-2">
        {/* Première page */}
        <button
          type="button"
          onClick={handleFirstPage}
          disabled={!canGoFirst || disabled}
          className={cn(
            'p-2 rounded-md transition-colors',
            'text-gray-600 dark:text-gray-400',
            'hover:bg-gray-100 dark:hover:bg-gray-800',
            'focus:outline-none focus:ring-2 focus:ring-blue-500',
            (!canGoFirst || disabled) && 'opacity-50 cursor-not-allowed',
          )}
          aria-label="Aller à la première page"
        >
          <ChevronsLeft className="h-5 w-5" aria-hidden="true" />
          <span className="sr-only">Première page</span>
        </button>

        {/* Page précédente */}
        <button
          type="button"
          onClick={handlePreviousPage}
          disabled={!canGoPrevious || disabled}
          className={cn(
            'p-2 rounded-md transition-colors',
            'text-gray-600 dark:text-gray-400',
            'hover:bg-gray-100 dark:hover:bg-gray-800',
            'focus:outline-none focus:ring-2 focus:ring-blue-500',
            (!canGoPrevious || disabled) && 'opacity-50 cursor-not-allowed',
          )}
          aria-label="Page précédente"
        >
          <ChevronLeft className="h-5 w-5" aria-hidden="true" />
          <span className="sr-only">Page précédente</span>
        </button>

        {/* Numéros de page */}
        {showPageNumbers && (
          <div className="flex items-center gap-1">
            {visiblePages[0] > 1 && (
              <>
                <button
                  type="button"
                  onClick={() => handlePageClick(1)}
                  disabled={disabled}
                  className={cn(
                    'px-3 py-1.5 rounded-md text-sm font-medium transition-colors',
                    'text-gray-700 dark:text-gray-300',
                    'hover:bg-gray-100 dark:hover:bg-gray-800',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500',
                    disabled && 'opacity-50 cursor-not-allowed',
                  )}
                  aria-label="Aller à la page 1"
                >
                  1
                </button>
                {visiblePages[0] > 2 && (
                  <span className="px-2 text-gray-500 dark:text-gray-400">
                    ...
                  </span>
                )}
              </>
            )}

            {visiblePages.map((page) => (
              <button
                key={page}
                type="button"
                onClick={() => handlePageClick(page)}
                disabled={disabled}
                className={cn(
                  'px-3 py-1.5 rounded-md text-sm font-medium transition-colors',
                  'focus:outline-none focus:ring-2 focus:ring-blue-500',
                  page === currentPage
                    ? 'bg-blue-600 text-white dark:bg-blue-500'
                    : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800',
                  disabled && 'opacity-50 cursor-not-allowed',
                )}
                aria-label={`Aller à la page ${page}`}
                aria-current={page === currentPage ? 'page' : undefined}
              >
                {page}
              </button>
            ))}

            {visiblePages[visiblePages.length - 1] < totalPages && (
              <>
                {visiblePages[visiblePages.length - 1] < totalPages - 1 && (
                  <span className="px-2 text-gray-500 dark:text-gray-400">
                    ...
                  </span>
                )}
                <button
                  type="button"
                  onClick={() => handlePageClick(totalPages)}
                  disabled={disabled}
                  className={cn(
                    'px-3 py-1.5 rounded-md text-sm font-medium transition-colors',
                    'text-gray-700 dark:text-gray-300',
                    'hover:bg-gray-100 dark:hover:bg-gray-800',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500',
                    disabled && 'opacity-50 cursor-not-allowed',
                  )}
                  aria-label={`Aller à la page ${totalPages}`}
                >
                  {totalPages}
                </button>
              </>
            )}
          </div>
        )}

        {/* Page suivante */}
        <button
          type="button"
          onClick={handleNextPage}
          disabled={!canGoNext || disabled}
          className={cn(
            'p-2 rounded-md transition-colors',
            'text-gray-600 dark:text-gray-400',
            'hover:bg-gray-100 dark:hover:bg-gray-800',
            'focus:outline-none focus:ring-2 focus:ring-blue-500',
            (!canGoNext || disabled) && 'opacity-50 cursor-not-allowed',
          )}
          aria-label="Page suivante"
        >
          <ChevronRight className="h-5 w-5" aria-hidden="true" />
          <span className="sr-only">Page suivante</span>
        </button>

        {/* Dernière page */}
        <button
          type="button"
          onClick={handleLastPage}
          disabled={!canGoLast || disabled}
          className={cn(
            'p-2 rounded-md transition-colors',
            'text-gray-600 dark:text-gray-400',
            'hover:bg-gray-100 dark:hover:bg-gray-800',
            'focus:outline-none focus:ring-2 focus:ring-blue-500',
            (!canGoLast || disabled) && 'opacity-50 cursor-not-allowed',
          )}
          aria-label="Aller à la dernière page"
        >
          <ChevronsRight className="h-5 w-5" aria-hidden="true" />
          <span className="sr-only">Dernière page</span>
        </button>
      </div>
    </div>
  );
}

export default TrackListPagination;
