import { StoryFn, StoryObj } from '@storybook/react-webpack5';
import React from 'react';

import Button from '../button';

import SegmentedControl from './SegmentedControl';

export default {
  component: SegmentedControl,
  title: 'Forms/SegmentedControl',
};

type Story = StoryObj<typeof SegmentedControl>;

const Template: Story = {
  render: (args) => {
    const [segments, setSegments] = React.useState([
      { id: 'CUPCAKE', label: 'Cupcakes', value: 'cupcakes' },
      { id: 'SPONGECAKE', label: 'Sponge cake', value: 'spongecake' },
      { id: 'CARROT_CAKE', label: 'Carrot cake', value: 'carrotcake' },
    ]);

    const [segmentsWithControls, setSegmentsWithControls] = React.useState([
      { id: 'CUPCAKE', label: 'Cupcakes', value: 'cupcakes', controls: 'aControlId' },
      { id: 'SPONGECAKE', label: 'Sponge cake', value: 'spongecake', controls: 'aControlId' },
      { id: 'CARROT_CAKE', label: 'Carrot cake', value: 'carrotcake', controls: 'aControlId' },
    ]);

    const [value, setValue] = React.useState(segments[0].value);

    console.log('render: segments.length', segments.length);
    return (
      <div className="p-a-2">
        <SegmentedControl
          name="aSegmentedControl"
          value={value}
          onChange={setValue}
          {...(args.mode === 'view'
            ? { segments: segmentsWithControls, mode: 'view', controls: 'aControlId' }
            : { segments, mode: 'input' })}
        />
        <div className="m-a-2" id="aControlId">
          <p>Selected value: {value}</p>
        </div>
        <div className="m-a-2">
          <p>
            Force the <b>selectedValue</b> to be one of the following:
            <ul>
              {segments.map((segment) => (
                <li key={segment.id}>
                  <a
                    href="/"
                    onClick={(e) => {
                      e.preventDefault();
                      setValue(segment.value);
                    }}
                  >
                    {segment.label}
                  </a>
                </li>
              ))}
            </ul>
          </p>
        </div>
        <div className="m-a-2">
          <Button
            priority="secondary"
            type="danger"
            size="sm"
            disabled={segments.length < 2}
            onClick={() => {
              const index = segments.findIndex((s) => s.value !== value);
              setSegments((prev) => prev.filter((_, i) => i !== index));
              setSegmentsWithControls((prev) => prev.filter((_, i) => i !== index));
            }}
          >
            Remove one segment
          </Button>
        </div>
      </div>
    );
  },
};

export const SegmentedControlDefault: Story = {
  ...Template,
  args: {
    mode: 'input',
  },
};

export const SegmentedControlView: Story = {
  ...Template,
  args: {
    mode: 'view',
  },
};
