import * as React from 'react'
import { Menu } from '@planview/pv-icons'
import { DropdownMenu, ListItemDivider } from '@planview/pv-uikit'
import { ToolbarSection } from '.'
import ResizeContext, {
    MoreMenuContext,
    MoreMenuProvider,
} from '../utils/context'
import { COLLAPSE_BELOW, MoreMenuButton } from '../more-menu'

export type ToolbarSectionRightProps = {
    /** content of the section  */
    children: React.ReactNode | React.ReactNode[]

    /** label for the more menu  */
    moreMenuLabel?: string
}

export type ToolbarSectionWithMenuProps = ToolbarSectionRightProps

const ToolbarSectionRightInner = ({
    children,
    moreMenuLabel,
}: ToolbarSectionRightProps) => {
    const { shouldDisplay } = React.useContext(ResizeContext)
    const { registeredItems, customMoreMenu } =
        React.useContext(MoreMenuContext)

    const dropdownChildren = React.useMemo(
        () =>
            registeredItems
                .filter((c) => shouldDisplay(c.displayOn))
                .map((c) => c.child),
        [shouldDisplay, registeredItems]
    )

    const shouldShowMoreMenu = React.useMemo((): boolean => {
        if (customMoreMenu) {
            return true
        }
        return !!dropdownChildren.length
    }, [dropdownChildren.length, customMoreMenu])

    const dropDownContent = React.useMemo(() => {
        const centerContent = dropdownChildren
        const hasCustomContent = !!customMoreMenu?.children
        const divider =
            hasCustomContent && centerContent?.length ? (
                <ListItemDivider key="custom-content-divider" />
            ) : null

        if (customMoreMenu?.collapse === COLLAPSE_BELOW) {
            return (
                <>
                    {customMoreMenu.children}
                    {divider}
                    {centerContent}
                </>
            )
        }

        return (
            <>
                {centerContent}
                {divider}
                {customMoreMenu?.children}
            </>
        )
    }, [customMoreMenu, dropdownChildren])

    return (
        <ToolbarSection>
            {children}
            {shouldShowMoreMenu ? (
                <DropdownMenu
                    alignRight
                    label={moreMenuLabel || ''}
                    trigger={(props) => (
                        <MoreMenuButton
                            label={moreMenuLabel}
                            icon={
                                customMoreMenu?.icon ? (
                                    customMoreMenu.icon
                                ) : (
                                    <Menu />
                                )
                            }
                            activated={props['aria-expanded']}
                            {...props}
                        />
                    )}
                >
                    {dropDownContent}
                </DropdownMenu>
            ) : null}
        </ToolbarSection>
    )
}

/**
 * Implementation of the [Toolbar Right Section Specification](https://design.planview.com/components/toolbar/toolbar#right-section)
 *
 * This component has the ability to move buttons, dropdowns and button-groups inside a more menu depending on the overall width of the toolbar.
 *
 * _Note: This component was previously named `ToolbarSectionWithMenu`. It has been renamed to improve clarity._
 *
 * ### Responsive behavior with displayOn
 *
 * The `ToolbarSectionRight` component introduces the concept of `displayOn` to determine which buttons should collapse
 * into the more menu when adapting to smaller screens.
 *
 * - All buttons will move into the more menu based on their `displayOn` setting, and the current breakpoint.
 * Note: the breakpoint is based on the toolbar width, not the full page (if the toolbar is narrower than the page).
 *
 * ### Usage
 *
 * Even if you only need content on the right, you must supply a `ToolbarSectionLeft` to have the content render on the right:
 *
 * ```tsx
 * import { ToolbarContainer, ToolbarSectionLeft, ToolbarSectionRight } from '@planview/pv-toolbar'
 *
 * export const PageToolbar = () => (
 *     <ToolbarContainer>
 *         <ToolbarSectionLeft></ToolbarSectionLeft>
 *         <ToolbarSectionRight>
 *             ...
 *         </ToolbarSectionRight>
 *     </ToolbarContainer>
 * )
 * ```
 */
export const ToolbarSectionRight = ({
    children,
    moreMenuLabel,
}: ToolbarSectionRightProps) => (
    <MoreMenuProvider>
        <ToolbarSectionRightInner moreMenuLabel={moreMenuLabel}>
            {children}
        </ToolbarSectionRightInner>
    </MoreMenuProvider>
)

export const ToolbarSectionWithMenu = ToolbarSectionRight
