import React, { useState, useEffect } from 'react'
import { Tooltip } from 'antd'
import { useTranslations } from '../hooks/useTranslation'

const Pagination = ({
  currentPage = 1,
  totalPages = 1,
  onPageChange,
  showQuickJump = false,
  maxVisiblePages = 5,
  className = '',
  showResultsInfo = false,
  totalItems = 0,
  itemsPerPage = 10,
  startIndex = 0
}) => {
  const { t } = useTranslations()
  const [jumpInputValue, setJumpInputValue] = useState(currentPage.toString())

  // Update input value when currentPage changes
  useEffect(() => {
    setJumpInputValue(currentPage.toString())
  }, [currentPage])

  const handlePageChange = page => {
    if (
      page >= 1 &&
      page <= totalPages &&
      page !== currentPage &&
      onPageChange
    ) {
      onPageChange(page)
    }
  }

  const handleJumpInputChange = e => {
    const value = e.target.value
    // Allow empty string or valid numbers
    if (value === '' || /^\d+$/.test(value)) {
      setJumpInputValue(value)
    }
  }

  const handleJumpInputSubmit = () => {
    const page = parseInt(jumpInputValue)
    if (
      jumpInputValue !== '' &&
      !isNaN(page) &&
      page >= 1 &&
      page <= totalPages
    ) {
      handlePageChange(page)
    } else {
      // Reset to current page if invalid
      setJumpInputValue(currentPage.toString())
    }
  }

  const handleJumpInputKeyPress = e => {
    if (e.key === 'Enter') {
      handleJumpInputSubmit()
    }
  }

  const handleJumpInputBlur = () => {
    handleJumpInputSubmit()
  }

  // Generate page numbers to display
  const getPageNumbers = () => {
    const pages = []

    if (totalPages <= maxVisiblePages) {
      // Show all pages if total pages is less than or equal to max visible
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i)
      }
    } else {
      // Calculate start and end page numbers
      let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2))
      let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1)

      // Adjust start page if we're near the end
      if (endPage - startPage < maxVisiblePages - 1) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1)
      }

      // Add first page and ellipsis if needed
      if (startPage > 1) {
        pages.push(1)
        if (startPage > 2) {
          pages.push('...')
        }
      }

      // Add visible page numbers
      for (let i = startPage; i <= endPage; i++) {
        pages.push(i)
      }

      // Add ellipsis and last page if needed
      if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
          pages.push('...')
        }
        pages.push(totalPages)
      }
    }

    return pages
  }

  const pageNumbers = getPageNumbers()
  const getEndIndex = () => {
    const endIndex = Math.min(
      parseInt(startIndex) + parseInt(itemsPerPage),
      totalItems
    )
    return endIndex
  }

  if (totalPages <= 1) {
    return null // Don't show pagination if there's only one page or no pages
  }

  return (
    <div className={`arcm-pagination-wrapper ${className}`}>
      {/* Single inline layout with results info, pagination controls, and quick jump */}
      <div className='arcm-flex arcm-items-center arcm-justify-between arcm-w-full'>
        {/* Left side - Results Info */}
        <div className='arcm-text-sm arcm-text-gray-700'>
          {showResultsInfo && totalItems > 0 && (
            <span>
              {t('showing_results')
                .replace('%1$s', startIndex + 1)
                .replace('%2$s', getEndIndex())
                .replace('%3$s', totalItems)}
            </span>
          )}
        </div>

        {/* Center - Pagination Controls and Quick Jump */}
        <div className='arcm-flex arcm-items-center arcm-gap-6'>
          {/* Pagination Controls */}
          <div className='arcm-flex arcm-items-center'>
            {/* Previous Button */}
            <button
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              className={`
                arcm-flex arcm-items-center arcm-justify-center arcm-w-10 arcm-h-10 arcm-text-sm arcm-font-medium arcm-transition-all arcm-duration-200 arcm-border arcm-border-r-0 arcm-rounded-l-md
                ${
                  currentPage === 1
                    ? 'arcm-text-gray-400 arcm-cursor-not-allowed arcm-bg-gray-50 arcm-border-gray-300'
                    : 'arcm-text-gray-600 arcm-bg-white arcm-border-gray-300 hover:arcm-bg-gray-50'
                }
              `}
              aria-label='Previous page'
            >
              <svg
                className='arcm-w-4 arcm-h-4'
                fill='none'
                stroke='currentColor'
                viewBox='0 0 24 24'
              >
                <path
                  strokeLinecap='round'
                  strokeLinejoin='round'
                  strokeWidth={1.5}
                  d='M15 19l-7-7 7-7'
                />
              </svg>
            </button>

            {/* Page Numbers */}
            {pageNumbers.map((page, index) => {
              const isFirst = index === 0
              const isLast = index === pageNumbers.length - 1

              return (
                <React.Fragment key={index}>
                  {page === '...' ? (
                    <span className='arcm-flex arcm-items-center arcm-justify-center arcm-w-10 arcm-h-10 arcm-text-sm arcm-text-gray-500 arcm-bg-white arcm-border-t arcm-border-b arcm-border-gray-300'>
                      ...
                    </span>
                  ) : (
                    <button
                      onClick={() => handlePageChange(page)}
                      className={`
                        arcm-flex arcm-items-center arcm-justify-center arcm-w-10 arcm-h-10 arcm-text-sm arcm-font-medium arcm-transition-all arcm-duration-200 arcm-border arcm-border-r-0 arcm-border-gray-300
                        ${
                          page === currentPage
                            ? 'arcm-bg-blue-600 arcm-text-white arcm-border-blue-600'
                            : 'arcm-text-gray-700 arcm-bg-white hover:arcm-bg-gray-50'
                        }
                      `}
                      aria-label={`Go to page ${page}`}
                      aria-current={page === currentPage ? 'page' : undefined}
                    >
                      {page}
                    </button>
                  )}
                </React.Fragment>
              )
            })}

            {/* Next Button */}
            <button
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              className={`
                arcm-flex arcm-items-center arcm-justify-center arcm-w-10 arcm-h-10 arcm-text-sm arcm-font-medium arcm-transition-all arcm-duration-200 arcm-border arcm-rounded-r-md
                ${
                  currentPage === totalPages
                    ? 'arcm-text-gray-400 arcm-cursor-not-allowed arcm-bg-gray-50 arcm-border-gray-300'
                    : 'arcm-text-white arcm-bg-blue-600 arcm-border-blue-600 hover:arcm-bg-blue-700'
                }
              `}
              aria-label='Next page'
            >
              <svg
                className='arcm-w-4 arcm-h-4'
                fill='none'
                stroke='currentColor'
                viewBox='0 0 24 24'
              >
                <path
                  strokeLinecap='round'
                  strokeLinejoin='round'
                  strokeWidth={1.5}
                  d='M9 5l7 7-7 7'
                />
              </svg>
            </button>
          </div>

          {/* Quick Jump Input Field */}
          {showQuickJump && totalPages > 1 && (
            <div className='arcm-flex arcm-items-center arcm-gap-2 arcm-text-sm arcm-text-gray-600'>
              <span>{t('go_to_page')}</span>
              <input
                type='text'
                inputMode='numeric'
                pattern='[0-9]*'
                value={jumpInputValue}
                onChange={handleJumpInputChange}
                onKeyPress={handleJumpInputKeyPress}
                onBlur={handleJumpInputBlur}
                placeholder={currentPage.toString()}
                className='arcm-w-16 arcm-px-2 arcm-py-1 arcm-border arcm-border-gray-300 arcm-rounded arcm-text-center arcm-text-sm focus:arcm-outline-none focus:arcm-ring-2 focus:arcm-ring-blue-500 focus:arcm-border-blue-500'
              />
              <Tooltip
                className=' arcm-text-sm'
                placement='top'
                title={t('type_page_number_enter')}
                color='#fff'
              >
                <span className='icon arcm-inline-flex'>
                  <svg
                    xmlns='http://www.w3.org/2000/svg'
                    width='14'
                    height='13'
                    viewBox='0 0 14 13'
                    fill='none'
                  >
                    <path
                      fill-rule='evenodd'
                      clip-rule='evenodd'
                      d='M13.4001 6.49998C13.4001 10.0346 10.5347 12.9 7.0001 12.9C3.46548 12.9 0.600098 10.0346 0.600098 6.49998C0.600098 2.96535 3.46548 0.0999756 7.0001 0.0999756C10.5347 0.0999756 13.4001 2.96535 13.4001 6.49998ZM6.15157 4.05143C5.91725 4.28574 5.53736 4.28574 5.30304 4.05143C5.06873 3.81711 5.06873 3.43721 5.30304 3.2029C6.2403 2.26564 7.75989 2.26564 8.69715 3.2029C9.63441 4.14016 9.63441 5.65975 8.69715 6.59701C8.38317 6.911 8.00238 7.12048 7.6001 7.22404V7.49995C7.6001 7.83132 7.33147 8.09995 7.0001 8.09995C6.66873 8.09995 6.4001 7.83132 6.4001 7.49995V7.09995C6.4001 6.52372 6.85605 6.16258 7.26517 6.07055C7.47868 6.02252 7.68138 5.91573 7.84863 5.74848C8.31725 5.27985 8.31725 4.52006 7.84863 4.05143C7.38 3.5828 6.6202 3.5828 6.15157 4.05143ZM7.0001 10.5C7.44192 10.5 7.8001 10.1418 7.8001 9.69998C7.8001 9.25815 7.44192 8.89997 7.0001 8.89997C6.55827 8.89997 6.2001 9.25815 6.2001 9.69998C6.2001 10.1418 6.55827 10.5 7.0001 10.5Z'
                      fill='#D1D5DB'
                    />
                  </svg>
                </span>
              </Tooltip>
              <span>{t('of_pages').replace('%s', totalPages)}</span>
            </div>
          )}
        </div>

        {/* Right side - placeholder for balance if needed */}
        <div className='arcm-w-0'></div>
      </div>
    </div>
  )
}

export default Pagination
