import React from 'react';
import styled from 'styled-components';

import type { ReactNode, JSX } from 'react';
import type { DropdownMenuItemProps } from '@redocly/theme/components/Dropdown/DropdownMenuItem';

import { DropdownMenuItem } from '@redocly/theme/components/Dropdown/DropdownMenuItem';

export type DropdownMenuProps = { className?: string; role?: string; footer?: React.ReactNode } & (
  | {
      items: DropdownMenuItemProps[];
    }
  | { children?: ReactNode }
);

export function DropdownMenu(props: DropdownMenuProps): JSX.Element {
  let content: React.ReactNode = null;

  if ('children' in props) {
    content = props.children;
  }

  if ('items' in props) {
    content = props.items.map((item, idx) => (
      <DropdownMenuItem key={idx} {...item}>
        {item.content}
      </DropdownMenuItem>
    ));
  }

  return (
    <DropdownMenuWrapper
      data-component-name="Dropdown/DropdownMenu"
      data-testid="dropdown-menu"
      className={props.className}
      role={props.role || 'menu'}
    >
      {content}
      {props.footer || null}
    </DropdownMenuWrapper>
  );
}

const DropdownMenuWrapper = styled.ul`
  font-size: var(--dropdown-menu-font-size);
  font-weight: var(--dropdown-menu-font-weight);
  line-height: var(--dropdown-menu-line-height);
  color: var(--dropdown-menu-text-color);

  /* Make sure the spacing is not overriden by the markdown list styles */
  --md-list-margin: 0;
  --md-list-left-padding: var(--dropdown-menu-padding);

  margin: 0;
  min-width: var(--dropdown-menu-min-width);
  max-width: var(--dropdown-menu-max-width);
  max-height: var(--dropdown-menu-max-height);
  padding: var(--dropdown-menu-padding);
  background-color: var(--dropdown-menu-bg-color);
  border-radius: var(--dropdown-menu-border-radius);
  box-shadow: var(--dropdown-menu-box-shadow);
  border: 1px solid var(--dropdown-menu-border-color);
  list-style-type: none;
  white-space: nowrap;
  overflow-x: hidden;
  overflow-y: auto;
  z-index: var(--z-index-surface);

  display: flex;
  flex-direction: column;
  gap: var(--dropdown-menu-item-gap);
`;
