import React, { type FC, useEffect, useState } from "react";
import { Decorator, Meta, StoryFn } from "@storybook/react";
import { MultipleButtonToggle, ThemeProviderWithStyledEngine } from "../";
import type { MultipleButtonToggleProps } from "../components/multipleButtonToggle/MultipleButtonToggle";
import type { IconProps } from "../components/icon/Icon";

interface AdditionalControls {
  groupWidth: number;
  buttons: Array<
    { value: string } & (
      | { text: string; icon?: undefined; "aria-label"?: undefined }
      | { icon: IconProps["name"]; text?: undefined; "aria-label": string }
    )
  >;
}

const decorator: Decorator<unknown> = (Story) => (
  <ThemeProviderWithStyledEngine>{Story()}</ThemeProviderWithStyledEngine>
);

const meta = {
  title: "Components/Inputs/MultipleButtonToggle",
  component: MultipleButtonToggle as FC<
    MultipleButtonToggleProps & AdditionalControls
  >,
  decorators: [decorator],
  argTypes: {
    groupWidth: {
      name: "Width of the group",
      control: {
        type: "range",
        min: 100,
        max: 700,
        step: 50,
      },
    },
    buttons: {
      name: "Buttons",
      description:
        "Use the raw editor to add objects with a required `value`, and either `text` or `icon`, but not both",
      control: "object",
    },
    onValueChange: {
      table: {
        disable: true,
      },
    },
    size: {
      name: "Size",
      control: "select",
      options: ["small", "large"],
    },
  },
} satisfies Meta<FC<MultipleButtonToggleProps & AdditionalControls>>;

export default meta;

const Template: StoryFn<FC<MultipleButtonToggleProps & AdditionalControls>> = (
  args
) => {
  const [value, setValue] = useState(args.value);
  useEffect(() => setValue(args.value), [args.value]);

  return (
    <div style={{ width: args.groupWidth }}>
      <MultipleButtonToggle
        value={value}
        onValueChange={setValue}
        size={args.size}
      >
        {args.buttons.map((button) => {
          if (button.text !== undefined) {
            return (
              <MultipleButtonToggle.Item
                key={button.value}
                value={button.value}
              >
                {button.text}
              </MultipleButtonToggle.Item>
            );
          } else {
            return (
              <MultipleButtonToggle.Item
                key={button.value}
                value={button.value}
                icon={button.icon}
                aria-label={button["aria-label"]}
              />
            );
          }
        })}
      </MultipleButtonToggle>
    </div>
  );
};

export const Default: StoryFn<
  FC<MultipleButtonToggleProps & AdditionalControls>
> = Template.bind({});

Default.args = {
  value: "1",
  groupWidth: 200,
  size: "large",
  buttons: [
    { text: "Active", value: "1" },
    { icon: "doc", value: "2", "aria-label": "Document" },
  ],
};
