import { Button } from "../button";
import {
  StyledContent,
  StyledItemList,
  StyledLabel,
  StyledLink,
  StyledMenuItem,
  StyledRoot,
  StyledTrigger,
  StyledViewport,
  ViewportPosition,
} from "./navigation-menu.styled";

type MenuListItem =
  | {
      label: string | React.ReactElement<{ children: string }>;
      content: React.ReactNode;
    }
  | {
      label: React.ReactElement<{ children: string }>;
      content?: never;
    };

export interface NavigationMenuProps extends React.ComponentProps<typeof StyledRoot> {
  items: MenuListItem[];
  itemListProps?: React.ComponentProps<typeof StyledItemList>;
  menuItemProps?: React.ComponentProps<typeof StyledMenuItem>;
  triggerProps?: React.ComponentProps<typeof StyledTrigger>;
  contentProps?: React.ComponentProps<typeof StyledContent>;
  buttonProps?: Omit<React.ComponentProps<typeof Button>, "text">;
  labelProps?: React.ComponentProps<typeof StyledLabel>;
  linkProps?: React.ComponentProps<typeof StyledLink>;
}

export const NavigationMenu: React.FC<NavigationMenuProps> = ({
  items,
  itemListProps,
  menuItemProps,
  triggerProps,
  contentProps,
  buttonProps,
  labelProps,
  linkProps,
  ...rootProps
}) => {
  return (
    <StyledRoot {...rootProps}>
      <StyledItemList {...itemListProps}>
        {items.map((item, index) => {
          return (
            <StyledMenuItem key={index} {...menuItemProps}>
              {"content" in item ? (
                <>
                  <StyledTrigger asChild {...triggerProps}>
                    {typeof item.label === "string" ? (
                      <Button variant="ghost" {...buttonProps} text={item.label} />
                    ) : (
                      <StyledLabel tabIndex={0} {...labelProps} variant="ghost" size="l">
                        {item.label}
                      </StyledLabel>
                    )}
                  </StyledTrigger>
                  <StyledContent {...contentProps}>{item.content}</StyledContent>
                </>
              ) : (
                <StyledLink variant="ghost" asChild {...linkProps}>
                  {item.label}
                </StyledLink>
              )}
            </StyledMenuItem>
          );
        })}
      </StyledItemList>

      <ViewportPosition>
        <StyledViewport />
      </ViewportPosition>
    </StyledRoot>
  );
};

export default NavigationMenu;
