import type { Meta, StoryObj } from '@storybook/react';
import { expect, userEvent, within } from 'storybook/test';
import { Switch } from './switch';
import { Label } from '../label';
import React from 'react';

const meta: Meta<typeof Switch> = {
  title: 'UI/Switch',
  component: Switch,
  render: args => <Switch {...args} />,
  argTypes: {
    checked: {
      control: 'boolean',
      description: 'The controlled checked state of the switch.',
    },
    disabled: {
      control: 'boolean',
      description: 'Whether the switch is disabled.',
    },
    size: {
      control: 'select',
      options: ['sm', 'md', 'lg'],
      description: 'Size variant — matches the form sizing scale.',
    },
  },
};

export default meta;
type Story = StoryObj<typeof Switch>;

export const Default: Story = {
  render: args => (
    <div className="flex items-center space-x-2">
      <Switch {...args} id="airplane-mode" />
      <Label htmlFor="airplane-mode">Airplane Mode</Label>
    </div>
  ),
};

export const Disabled: Story = {
  render: () => (
    <div className="flex items-center space-x-2">
      <Switch id="airplane-mode-disabled" disabled />
      <Label htmlFor="airplane-mode-disabled">Airplane Mode</Label>
    </div>
  ),
};

/**
 * Size comparison: sm, md (default), lg side-by-side.
 */
export const Sizes: Story = {
  render: () => (
    <div className="flex flex-col gap-4">
      <div className="flex items-center space-x-2">
        <Switch id="sw-sm" size="sm" />
        <Label htmlFor="sw-sm" size="sm">
          Small (sm)
        </Label>
      </div>
      <div className="flex items-center space-x-2">
        <Switch id="sw-md" size="md" />
        <Label htmlFor="sw-md" size="md">
          Medium (md — default)
        </Label>
      </div>
      <div className="flex items-center space-x-2">
        <Switch id="sw-lg" size="lg" />
        <Label htmlFor="sw-lg" size="lg">
          Large (lg)
        </Label>
      </div>
    </div>
  ),
};

export const Toggle: Story = {
  render: () => (
    <div className="flex items-center space-x-2">
      <Switch id="play-switch" />
      <Label htmlFor="play-switch">Airplane Mode</Label>
    </div>
  ),
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    const switchEl = canvas.getByRole('switch');
    await expect(switchEl).toHaveAttribute('aria-checked', 'false');
    await userEvent.click(switchEl);
    await expect(switchEl).toHaveAttribute('aria-checked', 'true');
    await userEvent.click(switchEl);
    await expect(switchEl).toHaveAttribute('aria-checked', 'false');
  },
};
