import { Flag } from '@wise/art';
import { createSandboxStory, globalScope } from '../../.storybook/components/sandbox/SandboxEditor';
import RadioGroup, { RadioGroupProps, RadioGroupRadio } from './RadioGroup';
import { Field } from '../field/Field';
import { Meta, StoryObj } from '@storybook/react-webpack5';
import { fn } from 'storybook/test';
import { useState } from 'react';
import AvatarView from '../avatarView';

const meta = {
  component: RadioGroup,
  title: 'Forms/RadioGroup',
} satisfies Meta<typeof RadioGroup>;

export default meta;
type Story<T extends string | number = string> = StoryObj<RadioGroupProps<T>>;

export const Sandbox = createSandboxStory({
  code: `const App = () => {
  const [selectedValue, setSelectedValue] = React.useState('radio-1');

  return (
    <Field label="Choose an option">
      <RadioGroup
        name="radio-group"
        selectedValue={selectedValue}
        onChange={(value) => setSelectedValue(value)}
        radios={[
          { value: 'radio-1', label: 'Option 1', secondary: 'Description for option 1' },
          { value: 'radio-2', label: 'Option 2', secondary: 'Description for option 2' },
          { value: 'radio-3', label: 'Option 3', secondary: 'Description for option 3' },
        ]}
      />
    </Field>
  );
};`,
  scope: globalScope,
});

export const Basic: Story = {
  args: {
    selectedValue: 'radio-2',
    name: 'radio-group',
    radios: [
      {
        value: 'radio-1',
        label: 'Radio1',
        secondary: 'Secondary line 1',
        disabled: false,
      },
      {
        value: 'radio-2',
        label: 'Radio2',
        disabled: false,
      },
      {
        value: 'radio-3',
        label: 'Radio3',
        secondary: 'Secondary line 3',
        disabled: true,
      },
    ],
    onChange: fn(),
  },
} satisfies Story;

export const WithAvatars = {
  ...Basic,
  args: {
    ...Basic.args,
    radios: Basic?.args?.radios?.map(
      (radio) =>
        ({
          ...radio,
          avatar: (
            <AvatarView>
              <Flag code="NZD" />
            </AvatarView>
          ),
        }) satisfies RadioGroupRadio,
    ),
  },
} satisfies Story;

export const WithinField = {
  ...Basic,
  render: function Render(args) {
    const [selectedValue, setSelectedValue] = useState('radio-2');
    const hasError = selectedValue === 'radio-2';
    return (
      <Field
        label="Field label"
        description="Field description"
        {...(hasError
          ? {
              message: 'Something went wrong',
              sentiment: 'negative',
            }
          : undefined)}
      >
        <RadioGroup {...args} selectedValue={selectedValue} onChange={setSelectedValue} />
      </Field>
    );
  },
} satisfies Story;
