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

import {
  ComboboxRoot,
  ComboboxInputGroup,
  ComboboxInput,
  ComboboxClear,
  ComboboxTrigger,
  ComboboxPopup,
  ComboboxList,
  ComboboxItem,
  ComboboxItemIndicator,
  ComboboxEmpty,
} from './combobox'

const fruits = ['Apple', 'Apricot', 'Banana', 'Cherry']

function ComboboxDemo() {
  const [value, setValue] = useState<string | null>(null)

  return (
    <ComboboxRoot<string | null>
      items={fruits}
      value={value}
      onValueChange={setValue}
      itemToStringLabel={(item) => item ?? ''}
      isItemEqualToValue={(a, b) => a === b}
    >
      <ComboboxInputGroup>
        <ComboboxInput placeholder='Pick a fruit' />
        <ComboboxClear aria-label='Clear' />
        <ComboboxTrigger aria-label='Open' />
      </ComboboxInputGroup>
      <ComboboxPopup>
        <ComboboxEmpty>No matches</ComboboxEmpty>
        <ComboboxList>
          {(item: string) => (
            <ComboboxItem key={item} value={item}>
              <ComboboxItemIndicator className='text-primary'>✓</ComboboxItemIndicator>
              {item}
            </ComboboxItem>
          )}
        </ComboboxList>
      </ComboboxPopup>
    </ComboboxRoot>
  )
}

const meta = {
  component: ComboboxDemo,
  tags: ['ai-generated'],
} satisfies Meta<typeof ComboboxDemo>

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {
  play: async ({ canvas }) => {
    await expect(canvas.getByPlaceholderText('Pick a fruit')).toBeInTheDocument()
  },
}
