import * as React from 'react'
import { ButtonGroup, ListGroup, ListItemDivider } from '@planview/pv-uikit'
import type { ToolbarButtonProps } from '../button'
import { WrappingParentContext } from '../utils/context'
import {
    ToolbarItem,
    ToolbarItemCollapsedView,
    ToolbarItemView,
} from '../wrapper'
import { transformButtonToListItem } from '../utils/section'
import type { DisplayOnType } from '../utils'
import { DISPLAY_ON_TABLET_PORTRAIT } from '../utils'

export type ToolbarButtonGroupProps = {
    /** Children need to be one of the ToolbarButtons */
    children: Array<React.ReactElement<
        Omit<ToolbarButtonProps, 'displayOn'>
    > | null>
    /** A11y: Label for group when rendered as dropdown group */
    groupLabel: string
    /**
     * Target display of the button group. Choose 'phone' to prevent collapsing.
     */
    displayOn?: DisplayOnType
}

/**
 *
 * `import { ToolbarButtonGroup } from '@planview/pv-toolbar' `
 *
 * **A note on displayOn:** In the \`ToolbarButtonGroup\` it does not make sense to give the individual buttons an \`displayOn\` and will be ignored.
 * This is because the \`ToolbarButtonGroup\` does the collapsing into the more menu and all buttons collapse at the same time.
 */
export const ToolbarButtonGroup = ({
    children,
    groupLabel,
    displayOn = DISPLAY_ON_TABLET_PORTRAIT,
}: ToolbarButtonGroupProps) => {
    //Make sure only children get passed to dropdown, remove null
    const filteredChildren = children.filter((c) => React.isValidElement(c))

    return (
        <ToolbarItem displayOn={displayOn}>
            <ToolbarItemView>
                {() => (
                    <WrappingParentContext.Provider
                        value={{ wrappedInToolbarParent: true }}
                    >
                        <ButtonGroup>{children}</ButtonGroup>
                    </WrappingParentContext.Provider>
                )}
            </ToolbarItemView>
            <ToolbarItemCollapsedView>
                <ListGroup label={groupLabel}>
                    {[
                        ...filteredChildren.map(transformButtonToListItem),
                        <ListItemDivider key="group-divider" />,
                    ]}
                </ListGroup>
            </ToolbarItemCollapsedView>
        </ToolbarItem>
    )
}
