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

import type { components } from '../api/schema'
import { LabelEditor } from './label-editor'

type LabelInput = components['schemas']['LabelInput']

// LabelEditor is controlled — drive it from local state so typing is reflected.
function ControlledLabelEditor({ value: initial }: { value: LabelInput[] }) {
  const [value, setValue] = useState<LabelInput[]>(initial)

  return <LabelEditor value={value} onChange={setValue} />
}

const meta = {
  component: LabelEditor,
  render: (args) => <ControlledLabelEditor value={args.value} />,
  args: { value: [], onChange: () => {} },
  tags: ['ai-generated'],
} satisfies Meta<typeof LabelEditor>

export default meta
type Story = StoryObj<typeof meta>

export const Empty: Story = {
  play: async ({ canvas }) => {
    await expect(canvas.getByLabelText('Label')).toHaveValue('')
  },
}

export const Prefilled: Story = {
  args: { value: [{ lang: 'sv', label: 'Brons' }] },
  play: async ({ canvas }) => {
    await expect(canvas.getByLabelText('Label')).toHaveValue('Brons')
  },
}

export const Editing: Story = {
  play: async ({ canvas, userEvent }) => {
    const input = canvas.getByLabelText('Label')
    await userEvent.type(input, 'Ceramic')
    await expect(input).toHaveValue('Ceramic')
  },
}

// An entry that already has labels in other languages (e.g. English) shows only the
// default-language label, with a hint that the other-language labels are preserved.
export const WithOtherLanguages: Story = {
  args: {
    value: [
      { lang: 'en', label: 'Bronze' },
      { lang: 'sv', label: 'Brons' },
    ],
  },
  play: async ({ canvas }) => {
    await expect(canvas.getByLabelText('Label')).toHaveValue('Brons')
    await expect(canvas.getByText(/other languages/i)).toBeInTheDocument()
  },
}
