import { chevronDown } from "@simplybusiness/icons";
import type { Meta, StoryObj } from "@storybook/react";
import classNames from "classnames/dedupe";
import type { Ref } from "react";
import type { DropdownMenuProps } from ".";
import { DropdownMenu } from ".";
import { excludeControls } from "../../utils";
import { StoryContainer } from "../../utils/StoryContainer";
import { Icon } from "../Icon";

import "./DropdownMenu.story.styles.css";

type StoryType = StoryObj<typeof DropdownMenu>;

const meta: Meta<typeof DropdownMenu> = {
  title: "Components/DropdownMenu",
  component: DropdownMenu,
  argTypes: excludeControls("trigger", "style"),
  decorators: [
    Story => (
      <StoryContainer>
        <Story />
      </StoryContainer>
    ),
  ],
};

type CustomTriggerProps = {
  ref?: Ref<HTMLButtonElement>;
  className?: string;
  open?: boolean;
};

const CustomTrigger = ({ ref, ...props }: CustomTriggerProps) => {
  const { className, open, ...otherProps } = props;
  const classes = classNames({
    "--is-open": open,
  });
  return (
    <button ref={ref} type="button" className={className} {...otherProps}>
      {open ? "Close" : "Open"} <Icon icon={chevronDown} className={classes} />
    </button>
  );
};
CustomTrigger.displayName = "CustomTrigger";

export const Default: StoryType = {
  render: (args: DropdownMenuProps) => (
    <div
      style={{
        height: 300,
      }}
    >
      <DropdownMenu {...args}>
        <DropdownMenu.Item>Home</DropdownMenu.Item>
        <DropdownMenu.Item>My details</DropdownMenu.Item>
        <DropdownMenu.Item>
          <a href="./?path=/docs/components-dropdownmenu--docs">Sign out</a>
        </DropdownMenu.Item>
      </DropdownMenu>
    </div>
  ),
  args: {
    label: "Menu",
  },
};

export const WithCustomTrigger: StoryType = {
  render: (args: DropdownMenuProps) => (
    <div
      style={{
        height: 300,
      }}
      className="dropdownmenu-example-custom-trigger"
    >
      <DropdownMenu {...args}>
        {}
        <DropdownMenu.Item onClick={() => alert("Clicked Home")}>
          Home
        </DropdownMenu.Item>
        <DropdownMenu.Item>My details</DropdownMenu.Item>
        <DropdownMenu.Item>Sign out</DropdownMenu.Item>
      </DropdownMenu>
    </div>
  ),
  args: {
    trigger: <CustomTrigger />,
  },
  parameters: {
    controls: {
      exclude: ["label"],
    },
  },
};

export default meta;
