import React from 'react';

import MediaQuery from 'react-responsive'

import { Button, Card, Flex, Box } from '@chakra-ui/react';

import { useTranslation } from 'react-i18next';
import { BookFilterElement } from '../constants/book';
import { MEDIA_QUERY_DESKTOP_STARTS, MEDIA_QUERY_MOBILE_ENDS } from '../constants/mediaquery';

interface IProps {
    setSortingElement(element: string): void
    activeFilter: string
    currentDirection: string
    elements: BookFilterElement[]
}

const DataFilter: React.FC<IProps> = (props) => {

    const { setSortingElement, activeFilter, currentDirection, elements } = props

    const { t } = useTranslation();

    const getSortingArrow = (sortButton: string) => {
        if (sortButton !== activeFilter) {
            return ''
        } else {
            return currentDirection == 'asc' ? <span>&nbsp; &#8595;</span> : <span>&nbsp; &#8593;</span>
        }
    }

    const getBox = (elem: BookFilterElement, key: number) => {
        return (
            <Box key={key} flex={elem.flex} p='4'>
                <Button
                    size={'xs'}
                    justifyContent={'space-between'}
                    onClick={() => { elem.sortable && setSortingElement(elem.field) }}>
                    {t(`book.${elem.field}`)} {getSortingArrow(elem.field)}
                </Button>
            </Box>
        )
    }

    const getFlexWrapper = () => {
        return (
            <Flex justifyContent={'space-between'}>
                {elements.map((elem, key) => {
                    return getBox(elem, key)
                })}
            </Flex>
        )
    }

    return (
        <>
            <MediaQuery minWidth={MEDIA_QUERY_DESKTOP_STARTS}>
                <Card backgroundColor={'transparent'} mt={{ base: 0, md: 4 }} mb={{ base: 0, md: 4 }} mx={{ base: 4, md: 8 }}>
                    {getFlexWrapper()}
                </Card>
            </MediaQuery>
            <MediaQuery maxWidth={MEDIA_QUERY_MOBILE_ENDS}>
                {getFlexWrapper()}
            </MediaQuery>
        </>

    );
}

export default DataFilter