import { action } from '@storybook/addon-actions';
import { Meta, StoryObj } from '@storybook/react';
import React, { useState } from 'react';
import { createGroups } from '../../../helpers/storybook';
import { CustomTags } from './CustomTags';

const groups = createGroups({
  Behavior: [
    'type',
    'autoFocus',
    'disabled',
    'inlineMode',
    'name',
    'id',
    'displayAsRows',
    'liveSuggestionsResolver',
    'liveSuggestionsDelay',
  ],
  Content: ['label', 'placeholder', 'error', 'tooltipContent', 'value'],
  Styling: ['className'],
  Events: ['onChange', 'onBlur', 'onFocus'],
});

const meta: Meta<typeof CustomTags> = {
  title: 'Primary Components/Form Elements/CustomTags',
  component: CustomTags,
  argTypes: {
    ...groups,
  },
};
export default meta;

export const Main: StoryObj<typeof CustomTags> = {
  args: {
    label: 'Genres',
    value: ['Drama', 'Comedy'],
    name: 'genres',
  },
  render: (args) =>
    React.createElement(() => {
      const [value, setValue] = useState(args.value);

      return (
        <CustomTags
          {...args}
          value={value}
          onChange={(e) => {
            action('onChange')(e);
            setValue(e.currentTarget.value as unknown as string[]);
          }}
        />
      );
    }),
};

const genres = [
  'Action',
  'Action 2',
  'Action 3',
  'Action 4',
  'Action 5',
  'Action 6',
  'Action 7',
  'Adventure',
  'Comedy',
  'Crime',
  'Drama',
  'Historical',
  'Horror',
  'Musical',
  'Science Fiction',
  'War',
  'Western',
];

const liveSuggestionsHandler = (val: string): Promise<string[]> => {
  return new Promise((resolve) => {
    action('Live Suggestion Requested')(val);
    setTimeout(() => {
      const items = genres
        .filter((genre) => genre.toLowerCase().startsWith(val.toLowerCase()))
        .sort();
      action('Live Suggestion Resolved')(val, items);
      resolve(items);
    }, 200);
  });
};

export const LiveSuggestions: StoryObj<typeof CustomTags> = {
  args: {
    label: 'Tags with Live Suggestions',
    value: ['Drama', 'Comedy'],
    name: 'genres',
  },
  render: (args) =>
    React.createElement(() => {
      {
        const [value, setValue] = useState(args.value);

        return (
          <CustomTags
            {...args}
            value={value}
            onChange={(e) => {
              action('onChange')(e);
              setValue(e.currentTarget.value as unknown as string[]);
            }}
            liveSuggestionsResolver={(value) => liveSuggestionsHandler(value)}
          />
        );
      }
    }),
};
