import React from 'react'
import {
    Flex,
    Grid,
    GridItem,
    IconButton,
    NumberDecrementStepper,
    NumberIncrementStepper,
    NumberInput,
    NumberInputField,
    NumberInputStepper,
    Select,
    Text,
    Tooltip,
    useColorModeValue,
    useMediaQuery,
} from '@chakra-ui/react'
import { ArrowLeftIcon, ArrowRightIcon, ChevronLeftIcon, ChevronRightIcon } from '@chakra-ui/icons'
import { useHookstate } from '@hookstate/core'
import { gameDashboardState } from '../stateManagement/gameState'
import { loadingState } from '../stateManagement/loadingState'
import { adminMode } from '../stateManagement/userState'
import getWithFilters from '../componentUtils/getWithFilters'
import { ratingState, steamRatingState } from "../stateManagement/ratingState";

export default function Pagination() {
    const gamesState = useHookstate(gameDashboardState)
    const games = gamesState.get()
    const admin = useHookstate(adminMode).get()
    const loadedState = useHookstate(loadingState)
    const pageIndex = games.count.currentPage
    const pageSize = games.count.limit
    const pageCount = games.count.pages
    const bg = useColorModeValue('gray.50', 'transparent')
    const useRatingState = useHookstate(ratingState).get()
    const useSteamRatingState = useHookstate(steamRatingState).get()
    const [isSmallerThan768] = useMediaQuery('(max-width: 768px)')

    const setPageSize = async (limit: number) => await getWithFilters(
        gamesState,
        loadedState,
        admin,
        games.count.currentPage,
        limit,
        games.searchParams,
        games.filters,
        useRatingState,
        useSteamRatingState
    )

    const gotoPage = async (page: number) => await getWithFilters(
        gamesState,
        loadedState,
        admin,
        page,
        games.count.limit,
        games.searchParams,
        games.filters,
        useRatingState,
        useSteamRatingState
    )

    const previousPage = async () => await getWithFilters(
        gamesState,
        loadedState,
        admin,
        games.pagination.prev.page,
        games.count.limit,
        games.searchParams,
        games.filters,
        useRatingState,
        useSteamRatingState
    )

    const nextPage = async () => await getWithFilters(
        gamesState,
        loadedState,
        admin,
        games.pagination.next.page,
        games.count.limit,
        games.searchParams,
        games.filters,
        useRatingState,
        useSteamRatingState
    )

    return (
        <Grid mb={'6'} justifyItems={{
            base: 'center'
        }} alignItems={{
            base: 'center'
        }} templateAreas={{
            base: `
                "backArrows pageNumber forwardArrows"
                "backArrows countPerPage forwardArrows"
                "backArrows gamesFound forwardArrows"
                   `,
            md: `"backArrows pageNumber goToPage countPerPage gamesFound forwardArrows"`
        }}>
            <GridItem area={"backArrows"}>
                <Flex>
                    <Tooltip label="First Page">
                        <IconButton
                            aria-label={'First Page'}
                            onMouseDown={() => gotoPage(0)}
                            isDisabled={pageIndex <= 1}
                            icon={<ArrowLeftIcon h={3} w={3} />}
                            mr={4}
                        />
                    </Tooltip>
                    <Tooltip label="Previous Page">
                        <IconButton
                            aria-label={'Previous Page'}
                            onMouseDown={previousPage}
                            isDisabled={pageIndex <= 1}
                            icon={<ChevronLeftIcon h={6} w={6} />}
                        />
                    </Tooltip>
                </Flex>
            </GridItem>
            <GridItem area={"pageNumber"}>
                <Text mr={{ md: 8 }}>
                    Page{' '}
                    <Text fontWeight="bold" as="span">
                        {pageIndex}
                    </Text>{' '}
                    of{' '}
                    <Text fontWeight="bold" as="span">
                        {pageCount}
                    </Text>
                </Text>
            </GridItem>
            {!isSmallerThan768 &&
                <GridItem area={"goToPage"}>
                    <Text mb={'1'}>Go to Page:</Text>
                    <NumberInput
                        bg={bg}
                        rounded={'md'}
                        w={{ base: 20, md: 28 }}
                        min={1}
                        max={pageCount}
                        value={pageIndex}
                        onChange={(value) => {
                            const page = value ? Number(value) : 1
                            gotoPage(page)
                        }}
                    >
                        <NumberInputField />
                        <NumberInputStepper>
                            <NumberIncrementStepper />
                            <NumberDecrementStepper />
                        </NumberInputStepper>
                    </NumberInput>

                </GridItem>
            }
            <GridItem area={"countPerPage"}>
                <Text mb={'1'}>Count Per Page:</Text>
                <Select
                    ml={{
                        base: '4',
                        md: '0'
                    }}
                    bg={bg}
                    rounded={'md'}
                    w={{ base: 20, md: 32 }}
                    value={pageSize}
                    onChange={(e) => {
                        setPageSize(Number(e.target.value))
                    }}
                >
                    {[10, 20, 30, 40, 50].map((pageSize) => (
                        <option key={pageSize} value={pageSize}>
                            {pageSize}
                        </option>
                    ))}
                </Select>
            </GridItem>
            <GridItem area={'gamesFound'}>
                <Text>Games Found: {games.count.totalGames}</Text>
            </GridItem>
            <GridItem area={"forwardArrows"}>
                <Flex justifySelf={'end'}>
                    <Tooltip label="Next Page">
                        <IconButton
                            aria-label={'Next Page'}
                            onMouseDown={nextPage}
                            isDisabled={pageIndex >= pageCount}
                            icon={<ChevronRightIcon h={6} w={6} />}
                        />
                    </Tooltip>
                    <Tooltip label="Last Page">
                        <IconButton
                            aria-label={'Last Page'}
                            onMouseDown={() => gotoPage(pageCount)}
                            isDisabled={pageIndex >= pageCount}
                            icon={<ArrowRightIcon h={3} w={3} />}
                            ml={4}
                        />
                    </Tooltip>
                </Flex>
            </GridItem>
        </Grid>
    )
}
