import {
  Button,
  Menu,
  MenuButton,
  Text,
  MenuItemOption,
  MenuList,
  MenuOptionGroup,
  Badge,
  HStack
} from "@chakra-ui/react";
import React, { useMemo } from "react";
import { ColumnInstance } from "react-table";
import { GroupIcon } from "./icons/GroupIcon";

export interface IGroupByProps {
  allColumns: ColumnInstance<any>[];
  toggleGroupBy: (columnId: string, value?: boolean) => void;
  groupBy: string[];
}

export const GroupBy = ({
  allColumns,
  toggleGroupBy,
  groupBy
}: IGroupByProps) => {
  const columns = useMemo(() => {
    return allColumns;
  }, []);
  return (
    <Menu closeOnSelect={false}>
      <MenuButton as={Button} leftIcon={<GroupIcon />} colorScheme="blue">
        <HStack spacing={1}>
          <Text fontSize="md">Group By </Text>
          {!!groupBy?.length && (
            <Badge bg="white" color="blue.600" borderRadius="full" size="md">
              {groupBy?.length}
            </Badge>
          )}
        </HStack>
      </MenuButton>
      <MenuList minWidth="240px">
        <MenuOptionGroup
          title="Group by"
          type="checkbox"
          defaultValue={groupBy}
          value={groupBy}
          onChange={(value) => {
            columns
              ?.filter((c) => c.canGroupBy)
              .map((col) => {
                if (value.includes(col.id)) {
                  !groupBy.includes(col.id) && toggleGroupBy(col.id, true);
                } else {
                  toggleGroupBy(col.id, false);
                }
              });
          }}
        >
          {columns
            ?.filter((c) => c.canGroupBy)
            .map((col) => (
              <MenuItemOption key={col.id} value={col.id}>
                <Text textTransform="capitalize" fontSize="md">
                  {col.Header}
                </Text>
              </MenuItemOption>
            ))}
        </MenuOptionGroup>
      </MenuList>
    </Menu>
  );
};
