import type { Meta, StoryObj } from '@storybook/react-vite'

import { expect } from 'storybook/test'

import { Input } from './Input'
import { TextField } from 'react-aria-components'

const meta: Meta<typeof Input> = {
  title: 'Components/Input',
  // @ts-expect-error Input does not support this, but wrapping <TextField> does
  component: ({ isInvalid, ...props }) => (
    <TextField isInvalid={isInvalid}>
      <Input {...props} />
    </TextField>
  ),
  argTypes: {},
}

export default meta

type Story = StoryObj<typeof Input>

export const Default: Story = {
  args: {
    label: 'Label',
    name: 'foo',
    required: false,
  },

  play: async ({ canvas, userEvent }) => {
    const textbox = canvas.getByRole('textbox')
    expect(textbox).not.toBeDisabled()

    expect(textbox).toHaveValue('')

    await userEvent.type(textbox, 'Hello World')
    expect(textbox).toHaveValue('Hello World')

    await userEvent.clear(textbox)
    expect(textbox).toHaveValue('')
  },
}

export const Filled: Story = {
  args: {
    label: 'Label',
    name: 'foo',
    value: 'Value',
  },

  play: async ({ canvas }) => {
    const textbox = canvas.getByRole('textbox')
    expect(textbox).toHaveValue('Value')

    expect(textbox).not.toBeDisabled()
  },
}

export const Error: Story = {
  args: {
    label: 'Label',
    name: 'foo',
    // @ts-expect-error Input does not support this, but wrapping <TextField> does
    isInvalid: true,
  },

  play: async ({ canvas }) => {
    const textbox = canvas.getByRole('textbox')
    expect(textbox).toHaveAttribute('aria-invalid', 'true')
    expect(textbox).not.toBeDisabled()
  },
}

export const Disabled: Story = {
  args: {
    label: 'Label',
    name: 'foo',
    disabled: true,
  },

  play: async ({ canvas, userEvent }) => {
    const textbox = canvas.getByRole('textbox')
    expect(textbox).toHaveValue('')
    expect(textbox).toBeDisabled()

    await userEvent.type(textbox, 'Hello World')
    expect(textbox).toHaveValue('')
  },
}

export const DisabledFilled: Story = {
  args: {
    label: 'Label',
    name: 'foo',
    disabled: true,
    value: 'Value',
  },

  play: async ({ canvas, userEvent }) => {
    const textbox = canvas.getByRole('textbox')
    expect(textbox).toHaveValue('Value')
    expect(textbox).toBeDisabled()

    await userEvent.type(textbox, 'Hello World')
    expect(textbox).toHaveValue('Value')
  },
}
