import { useState } from 'react'
import {
    Tag,
    Text,
    Button,
    Menu, MenuButton, MenuList, MenuItem, MenuOptionGroup, MenuItemOption, MenuDivider,
    Checkbox, 
} from '@chakra-ui/react'
import { ChevronDownIcon } from '@chakra-ui/icons'

import { tagColorMap } from './index'

const OrderStatusMenu = ({ statusFilters, setStatusFilters }: any) => {
    const statusesArr = Object.entries(statusFilters);
    const [isAllSelected, setAllSelected] = useState(false)
    const [values, setValues] = useState<string[]>([])

    const filterSetterAll = () => ({received: true, cancelled: true, fulfilled: true})
    const filterInArr = (selected: string[]) => {
        const pojo = filterSetterAll()
        for (const key in pojo) {
            if(!selected.includes(key)){
                // @ts-ignore
                pojo[key] = false;
            }
        }
        return pojo
    }

    const handleCheckboxGroup = (checkboxes: any) => {
        if (checkboxes.includes("all")) {
            setAllSelected(true)
            setValues(['all', ...Object.keys(statusFilters)])
            setStatusFilters(filterSetterAll())
        } else {
            setAllSelected(false)
            setValues(checkboxes)
            setStatusFilters(filterInArr(checkboxes))
        }
    }

    return (
        <Menu>
            <MenuButton 
                as={Button} 
                rightIcon={<ChevronDownIcon />}
            >
                Status
            </MenuButton>
            <MenuList>
                <MenuOptionGroup 
                    title="Status"  
                    type="checkbox" 
                    textTransform="uppercase"
                    value={values}
                    onChange={handleCheckboxGroup}
                >
                    <MenuItemOption 
                        textTransform="uppercase"
                        value="all" 
                    >All</MenuItemOption>   
                    <MenuDivider />
                    {statusesArr.map(([statusText, isChecked]) => (
                        <MenuItemOption
                            isDisabled={isAllSelected}
                            key={statusText}
                            value={statusText}
                            textTransform="uppercase"
                        >
                            <Tag colorScheme={tagColorMap.get(statusText.toUpperCase())}>{statusText}</Tag>
                            
                        </MenuItemOption>
                    ))}
                </MenuOptionGroup> 
            </MenuList>
        </Menu>
      )
}

export default OrderStatusMenu