import type { Meta, StoryObj } from "@storybook/vue3-vite"
import type { SelectOptionLike } from "@/definitions/shared/select-options"
import AsyncSelectPicker from "./AsyncSelectPicker.vue"
import { componentDoc } from "@/lib/storybook"

const USERS: SelectOptionLike[] = [
  { label: "Alice Anderson", value: "u1" },
  { label: "Bob Bennett", value: "u2" },
  { label: "Carol Chen", value: "u3" },
  { label: "Diego Diaz", value: "u4" },
  { label: "Eve Evans", value: "u5" },
]

function mockSearch(query: string): Promise<SelectOptionLike[]> {
  return new Promise((resolve) => {
    setTimeout(() => {
      const q = query.toLowerCase()
      resolve(
        USERS.filter((u) =>
          typeof u === "string"
            ? u.toLowerCase().includes(q)
            : u.label.toLowerCase().includes(q),
        ),
      )
    }, 300)
  })
}

const meta = {
  title: "Elements/Picker/AsyncSelectPicker",
  component: AsyncSelectPicker,
  tags: ["autodocs"],
  args: {
    label: "User",
    placeholder: "Pick a user…",
    onSearch: mockSearch,
  },
  parameters: componentDoc("AsyncSelectPicker", { barrel: "picker" }),
  decorators: [
    () => ({
      template: '<div class="w-96 p-4"><story /></div>',
    }),
  ],
} satisfies Meta<typeof AsyncSelectPicker>

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {
  args: { label: "User", onSearch: mockSearch },
}

export const WithInitialValue: Story = {
  args: {
    label: "User",
    onSearch: mockSearch,
    initialOptions: USERS,
    modelValue: "u2",
  },
}

export const Disabled: Story = {
  args: { label: "Disabled", disabled: true, onSearch: mockSearch },
}

export const Showcase: Story = {
  args: {} as never,
  render: () => ({
    components: { AsyncSelectPicker },
    setup() {
      return { onSearch: mockSearch, initial: USERS }
    },
    template: `
      <div class="flex flex-col gap-4 max-w-md">
        <AsyncSelectPicker label="Default" :on-search="onSearch" />
        <AsyncSelectPicker
          label="Initial value"
          :on-search="onSearch"
          :initial-options="initial"
          model-value="u2"
        />
        <AsyncSelectPicker
          label="Min length 3"
          :on-search="onSearch"
          :min-search-length="3"
        />
        <AsyncSelectPicker label="Disabled" disabled :on-search="onSearch" />
        <AsyncSelectPicker
          label="With errors"
          :on-search="onSearch"
          :errors="['Please pick a user.']"
        />
      </div>
    `,
  }),
}
