'use client';

import { FC } from 'react';
import { cn } from '@/utils/helpers';
import { Select } from '../Select';
import styles from './Pagination.module.scss';

export interface PaginationProps {
  current: number;
  pageSize: number;
  total: number;
  pageSizeOptions?: number[];
  onChange: (page: number, pageSize: number) => void;
  showSizeChanger?: boolean;
  showTotal?: boolean;
  className?: string;
}

export const Pagination: FC<PaginationProps> = ({
  current,
  pageSize,
  total,
  pageSizeOptions = [10, 20, 50, 100],
  onChange,
  showSizeChanger = true,
  showTotal = true,
  className,
}) => {
  const totalPages = Math.ceil(total / pageSize);

  const handlePageChange = (page: number) => {
    if (page < 1 || page > totalPages) return;
    onChange(page, pageSize);
  };

  const handlePageSizeChange = (size: number) => {
    onChange(1, size);
  };

  const renderPageNumbers = () => {
    const pages: (number | string)[] = [];
    const showEllipsis = totalPages > 7;

    if (!showEllipsis) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (current <= 4) {
        for (let i = 1; i <= 5; i++) {
          pages.push(i);
        }
        pages.push('...');
        pages.push(totalPages);
      } else if (current >= totalPages - 3) {
        pages.push(1);
        pages.push('...');
        for (let i = totalPages - 4; i <= totalPages; i++) {
          pages.push(i);
        }
      } else {
        pages.push(1);
        pages.push('...');
        for (let i = current - 1; i <= current + 1; i++) {
          pages.push(i);
        }
        pages.push('...');
        pages.push(totalPages);
      }
    }

    return pages.map((page, index) => {
      if (page === '...') {
        return (
          <span key={`ellipsis-${index}`} className={styles.pagination__ellipsis}>
            ...
          </span>
        );
      }

      return (
        <button
          key={page}
          className={cn(styles.pagination__item, page === current && styles['pagination__item--active'])}
          onClick={() => handlePageChange(page as number)}
        >
          {page}
        </button>
      );
    });
  };

  if (total === 0) return null;

  return (
    <div className={cn(styles.pagination, className)}>
      {showTotal && (
        <span className={styles.pagination__total}>
          共 <strong>{total}</strong> 条
        </span>
      )}

      <div className={styles.pagination__controls}>
        <button
          className={cn(styles.pagination__arrow, current === 1 && styles['pagination__arrow--disabled'])}
          onClick={() => handlePageChange(current - 1)}
          disabled={current === 1}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <polyline points="15 18 9 12 15 6" />
          </svg>
        </button>

        {renderPageNumbers()}

        <button
          className={cn(
            styles.pagination__arrow,
            current === totalPages && styles['pagination__arrow--disabled']
          )}
          onClick={() => handlePageChange(current + 1)}
          disabled={current === totalPages}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <polyline points="9 18 15 12 9 6" />
          </svg>
        </button>
      </div>

      {showSizeChanger && (
        <div className={styles.pagination__sizeChanger}>
          <Select
            size="sm"
            value={pageSize}
            options={pageSizeOptions.map((size) => ({
              label: `${size} 条/页`,
              value: size,
            }))}
            onChange={handlePageSizeChange}
          />
        </div>
      )}
    </div>
  );
};
