import { useState } from 'react';
import { Meta, StoryObj } from '@storybook/react-webpack5';
import { expect, userEvent, within } from 'storybook/test';
import { MultiCurrency } from '@transferwise/icons';
import List from '../../list';
import { ListItem, type ListItemProps } from '../ListItem';

export default {
  component: ListItem,
  title: 'Content/ListItem/Tests/Context Updates',
  tags: ['!autodocs', '!manifest'],
  parameters: {
    controls: { disable: true },
    actions: { disable: true },
    knobs: { disable: true },
  },
} satisfies Meta<ListItemProps>;

type Story = StoryObj<ListItemProps>;

/**
 * Test: Dynamic state updates should propagate through listItemContext to control subcomponents.
 * The Switch control toggles the disabled state of the ListItem.
 * When disabled changes, the Switch should correctly update its disabled state via the context.
 */
export const DisabledToggle: Story = {
  render: () => {
    const [disabled, setDisabled] = useState(false);

    return (
      <List>
        <ListItem
          disabled={disabled}
          title="Payment notifications"
          subtitle={`ListItem disabled: ${disabled ? 'true' : 'false'}`}
          media={
            <ListItem.AvatarView>
              <MultiCurrency />
            </ListItem.AvatarView>
          }
          control={<ListItem.Switch checked={!disabled} onClick={() => setDisabled(!disabled)} />}
        />
      </List>
    );
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    const switchControl = canvas.getByRole('switch');

    // Initial state: disabled should be false, switch should be enabled and checked
    await expect(switchControl).toBeEnabled();
    await expect(switchControl).toBeChecked();
    await expect(canvas.getByRole('listitem')).not.toHaveAttribute('aria-disabled', 'true');

    // Click switch to set disabled to true
    await userEvent.click(switchControl);

    // Verify switch is now disabled and unchecked
    await expect(switchControl).toBeDisabled();
    await expect(switchControl).not.toBeChecked();
    await expect(canvas.getByRole('listitem')).toHaveAttribute('aria-disabled', 'true');
  },
};
