import { StoryFn, Meta } from '@storybook/react';
import { useState } from 'react';

import Chips, { ChipsProps, ChipValue } from './Chips';

const meta: Meta<typeof Chips> = {
  title: 'Actions/Chips',
  component: Chips,
  tags: ['autodocs'],
};
export default meta;

type Story = StoryFn<ChipsProps>;

const FilterTemplate: Story = (args: ChipsProps) => {
  const [selected, setSelected] = useState<readonly ChipValue[]>(
    args.selected == null || Array.isArray(args.selected) ? args.selected : [args.selected],
  );
  return (
    <Chips
      {...args}
      selected={selected}
      multiple
      onChange={({ selectedValue, isEnabled }) => {
        if (isEnabled) {
          setSelected([...selected, selectedValue]);
        } else {
          const updatedSelected = selected.filter((value) => selectedValue !== value);
          setSelected(updatedSelected);
        }
      }}
    />
  );
};

const ChoiceTemplate: Story = (args: ChipsProps) => {
  const [selected, setSelected] = useState<ChipValue>(args.selected as ChipValue);
  return (
    <Chips
      {...args}
      selected={selected}
      onChange={({ selectedValue }) => setSelected(selectedValue)}
    />
  );
};

export const FilterChips: typeof FilterTemplate = FilterTemplate.bind({});
FilterChips.args = {
  chips: [
    {
      value: 'accounting',
      label: 'Accounting',
    },
    {
      value: 'payroll',
      label: 'Payroll',
    },
    {
      value: 'reporting',
      label: 'Reporting',
    },
    {
      value: 'payments',
      label: 'Payments',
    },
  ],
};

export const PreSelectedFilterChips: typeof FilterTemplate = FilterTemplate.bind({});
PreSelectedFilterChips.args = {
  chips: [
    {
      value: 'accounting',
      label: 'Accounting',
    },
    {
      value: 'payroll',
      label: 'Payroll',
    },
    {
      value: 'reporting',
      label: 'Reporting',
    },
    {
      value: 'payments',
      label: 'Payments',
    },
  ],
  selected: ['accounting', 'payments'],
};

export const ChoiceChips: typeof ChoiceTemplate = ChoiceTemplate.bind({});
ChoiceChips.args = {
  chips: [
    {
      value: 1,
      label: '100 GBP',
    },
    {
      value: 2,
      label: '200 GBP',
    },
    {
      value: 3,
      label: '300 GBP',
    },
    {
      value: 4,
      label: '400 GBP+',
    },
  ],
  selected: 3,
};
