import { Flex, Link, Select, Text } from '@chakra-ui/react'
import clsx from 'clsx'
import NextLink from 'next/link'
import { useRouter } from 'next/router'
import { Fragment } from 'react'

export default function Pagination({ page = 1, itemsPerPage = 12, totalItems = 0, limit = 3 }) {
  const router = useRouter()

  const totalPages = Math.ceil(totalItems / itemsPerPage)

  if (totalPages === 1) return <></>

  const links = new Array(totalPages)
    .fill(true)
    .map((_v, i) => (i < limit || i >= totalPages - limit || (i >= page - limit && i < page + limit - 1)) && i + 1)
    .filter((i) => i !== false)

  return (
    <>
      <Flex justifyContent="space-between" direction={['column', 'row']} mt={6} mb={6} gap={3}>
        <Link
          //
          as={NextLink}
          href={{ query: { ...router.query, page: Math.max(1, page - 1) } }}
          variant="pagination"
        >
          &larr; Previous
        </Link>
        <Flex gap={1} display={['none', 'none', 'flex']}>
          {links.map((v, i) => (
            <Fragment key={i}>
              {v > 1 && v - 1 !== links[i - 1] && (
                <Text marginX={3} lineHeight={10}>
                  &hellip;
                </Text>
              )}
              <Link
                //
                key={v}
                as={NextLink}
                prefetch={false}
                href={{ query: { ...router.query, page: v } }}
                className={clsx({
                  current: v === page,
                })}
                variant="pagination"
              >
                {v}
              </Link>
            </Fragment>
          ))}
        </Flex>
        <Select
          value={page}
          onChange={(v) => router.push({ query: { ...router.query, page: v.target.value } })}
          display={['flex', 'flex', 'none']}
          textAlign="center"
        >
          {new Array(totalPages).fill(true).map((v, i) => (
            <option value={i + 1} key={i}>
              {i + 1}
            </option>
          ))}
        </Select>
        <Link
          //
          as={NextLink}
          href={{ query: { ...router.query, page: Math.min(totalPages, page + 1) } }}
          variant="pagination"
          textAlign="right"
        >
          Next &rarr;
        </Link>
      </Flex>
    </>
  )
}
