import React, { useContext } from "react";
import { theme, styled } from "../theme";
import type * as WPDS from "../theme";
import { DropdownMenu as ActionMenuPrimitive } from "radix-ui";
import { Icon } from "../icon";
import { ChevronRight } from "@washingtonpost/wpds-assets";
import { ActionMenuContext } from "./context";
import { ItemStyles } from "./ActionMenuItem";

const NAME = "ActionMenuSubTrigger";

const SubTriggerStyles = {
  ...ItemStyles,
  "&[data-state=open]": {
    outline: "none",
    backgroundColor: theme.colors.alpha25,
  },
  variants: {
    density: {
      loose: {
        padding: theme.space["100"],
      },
      default: {
        padding: theme.space["075"],
      },
      compact: {
        padding: theme.space["050"],
      },
    },
  },
  defaultVariants: {
    density: "default",
  },
};

const RightIcon = styled(Icon, {
  width: theme.sizes["100"],
  color: theme.colors.accessible,
  fill: theme.colors.primary,
  display: "flex",
  marginLeft: "auto",
});

const StyledSubTrigger = styled(
  ActionMenuPrimitive.SubTrigger,
  SubTriggerStyles
);

export type ActionMenuSubTriggerProps = {
  /** Any React node may be used as a child to allow for formatting */
  children?: React.ReactNode;
  /** Override CSS */
  css?: WPDS.CSS;
  onClick?: () => void;
} & ActionMenuPrimitive.DropdownMenuSubTriggerProps;

export const ActionMenuSubTrigger = React.forwardRef<
  HTMLDivElement,
  ActionMenuSubTriggerProps
>(({ children, ...props }: ActionMenuSubTriggerProps, ref) => {
  const context = useContext(ActionMenuContext);

  return (
    <StyledSubTrigger
      {...props}
      ref={ref}
      className="action-menu-item"
      density={context.density}
    >
      {children}
      <RightIcon label="Expand submenu">
        <ChevronRight />
      </RightIcon>
    </StyledSubTrigger>
  );
});

ActionMenuSubTrigger.displayName = NAME;
