import { ReactNode, useState } from 'react'
import { Button } from './button'
import { ArrowLeftIcon, ArrowRightIcon } from '../icons/common'
import { cn } from '@/lib/utils/cn'

export const Pagination = ({
  items,
  countPerPage,
  gridSize,
}: {
  items: ReactNode[]
  countPerPage: number
  gridSize: Record<string, number>
}) => {
  const [activePage, setActivePage] = useState(0)
  const totalPages = Math.ceil(items.length / countPerPage)
  const startIdx = activePage * countPerPage
  const currentItems = items.slice(startIdx, startIdx + countPerPage)
  const gridClasses = cn(
    'inline-grid gap-4 mx-auto w-fit grid-cols-1',
    ...Object.entries(gridSize).map(([breakpoint, cols]) => `${breakpoint}:grid-cols-${cols}`),
  )

  return (
    <div className="lg:min-h-[1164px] flex flex-col justify-between">
      <div className="flex w-full justify-center">
        <div className={gridClasses}>{currentItems}</div>
      </div>
      <div className="mt-8 flex justify-between items-center sm:section container-padding sm:pl-0 sm:box sm:mx-0">
        <div className="flex gap-1.5 items-center">
          {Array.from({ length: totalPages }).map((_, i) => (
            <div
              key={i}
              onClick={() => setActivePage(i)}
              className={cn(
                'size-2 rounded-full transition-colors bg-grey-100 cursor-pointer',
                i === activePage && 'bg-grey-200 size-3',
              )}
            />
          ))}
        </div>

        <div className="flex items-center gap-4 p-1">
          <Button
            variant="secondary"
            iconOnly
            onClick={() => setActivePage((prev) => Math.max(prev - 1, 0))}
            disabled={activePage === 0}
            className="disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ArrowLeftIcon className="size-5 stroke-grey-50" />
          </Button>
          <Button
            variant="secondary"
            iconOnly
            onClick={() => setActivePage((prev) => Math.min(prev + 1, totalPages - 1))}
            disabled={activePage === totalPages - 1}
            className="disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ArrowRightIcon className="size-5 stroke-grey-50" />
          </Button>
        </div>
      </div>
    </div>
  )
}
