import type { Meta, StoryObj } from '@storybook/vue3-vite';
import { ref } from 'vue';
import { UiBadge } from '@/components/UiBadge';
import { UiCheckbox } from '@/components/UiCheckbox';
import UiAutocomplete from './UiAutocomplete.vue';
import UiAutocompleteItem from './UiAutocompleteItem.vue';

const fruits = [
  { value: 'apple', label: 'Apple' },
  { value: 'banana', label: 'Banana' },
  { value: 'orange', label: 'Orange' },
  { value: 'grape', label: 'Grape' },
  { value: 'mango', label: 'Mango' },
  { value: 'pear', label: 'Pear' },
];

const fruitsWithMeta = [
  { value: 'apple', label: 'Apple', group: 'Pome', status: 'Popular' },
  { value: 'banana', label: 'Banana', group: 'Tropical', status: 'Fresh' },
  { value: 'orange', label: 'Orange', group: 'Citrus', status: 'Vitamin C' },
  { value: 'grape', label: 'Grape', group: 'Berry', status: 'Seedless' },
  { value: 'mango', label: 'Mango', group: 'Tropical', status: 'Seasonal' },
  { value: 'pear', label: 'Pear', group: 'Pome', status: 'Ripe' },
];

/**
 * UiAutocomplete is a searchable select input. It supports single and multiple
 * selection, custom input and item slots, and truncates selected labels when
 * they exceed the input width.
 */
const meta: Meta<typeof UiAutocomplete> = {
  title: 'Components/UiAutocomplete',
  component: UiAutocomplete,
  tags: ['autodocs'],
  argTypes: {
    multiple: {
      control: 'boolean',
      description: 'Allow multiple selected options',
    },
    disabled: {
      control: 'boolean',
      description: 'Disable the autocomplete',
    },
  },
  args: {
    multiple: false,
    disabled: false,
  },
};

export default meta;

type Story = StoryObj<typeof UiAutocomplete>;

const defaultTemplateSource = `<script setup lang="ts">
import { ref } from 'vue'
import { UiAutocomplete } from '@aleph-alpha/ui-library'

const value = ref('')
const options = [
  { value: 'apple', label: 'Apple' },
  { value: 'banana', label: 'Banana' },
  { value: 'orange', label: 'Orange' },
]
</script>

<template>
  <UiAutocomplete v-model="value" :options="options" placeholder="Search fruit" class="w-[260px]" />
</template>`;

export const Default: Story = {
  render: (args) => ({
    components: { UiAutocomplete },
    setup() {
      const value = ref('');
      return { args, value, fruits };
    },
    template: `
      <UiAutocomplete
        v-model="value"
        v-bind="args"
        :options="fruits"
        placeholder="Search fruit"
        start-icon="search"
        class="w-[260px]"
      />
    `,
  }),
  parameters: {
    docs: {
      description: {
        story:
          'Basic searchable autocomplete using the `options` prop. Typing filters the dropdown, and selecting an option updates `v-model`.',
      },
      source: {
        code: defaultTemplateSource,
      },
    },
  },
};

const multipleTemplateSource = `<script setup lang="ts">
import { ref } from 'vue'
import { UiAutocomplete } from '@aleph-alpha/ui-library'

const value = ref<string[]>(['apple', 'banana', 'orange', 'grape'])
const options = [
  { value: 'apple', label: 'Apple' },
  { value: 'banana', label: 'Banana' },
  { value: 'orange', label: 'Orange' },
  { value: 'grape', label: 'Grape' },
]
</script>

<template>
  <UiAutocomplete
    v-model="value"
    multiple
    :options="options"
    placeholder="Search fruits"
    class="w-[220px]"
  />
</template>`;

export const Multiple: Story = {
  render: () => ({
    components: { UiAutocomplete },
    setup() {
      const value = ref(['apple', 'banana', 'orange', 'grape']);
      return { value, fruits };
    },
    template: `
      <div class="flex flex-col gap-3">
        <UiAutocomplete
          v-model="value"
          multiple
          :options="fruits"
          placeholder="Search fruits"
          class="w-[220px]"
        />
        <div class="text-xs text-content-on-surface-secondary">
          Selected: {{ value.join(', ') || 'None' }}
        </div>
      </div>
    `,
  }),
  parameters: {
    docs: {
      description: {
        story:
          'Multi-select autocomplete. Selected labels are rendered in the input and truncate with an ellipsis when they exceed the available width.',
      },
      source: {
        code: multipleTemplateSource,
      },
    },
  },
};

export const WithSlots: Story = {
  render: () => ({
    components: { UiAutocomplete },
    setup() {
      const value = ref('');
      return { value, fruits };
    },
    template: `
      <UiAutocomplete
        v-model="value"
        :options="fruits"
        placeholder="Search fruit"
        start-icon="search"
        class="w-[300px]"
      >
        <template #item="{ option, selected }">
          <div class="flex min-w-0 flex-1 items-center justify-between gap-2">
            <span class="truncate">{{ option.label }}</span>
            <span v-if="selected" class="text-xs text-muted-foreground">Selected</span>
          </div>
        </template>
      </UiAutocomplete>
    `,
  }),
  parameters: {
    docs: {
      description: {
        story:
          'Customizes option rows with the `item` slot while keeping the built-in filtering, keyboard navigation, and selection behavior.',
      },
    },
  },
};

export const WithBadges: Story = {
  render: () => ({
    components: { UiAutocomplete, UiBadge },
    setup() {
      const value = ref('');
      return { value, fruitsWithMeta };
    },
    template: `
      <UiAutocomplete
        v-model="value"
        :options="fruitsWithMeta"
        placeholder="Search fruit"
        start-icon="search"
        class="w-[340px]"
      >
        <template #item="{ option }">
          <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
            <span class="truncate">{{ option.label }}</span>
            <div class="flex shrink-0 items-center gap-1.5">
              <UiBadge variant="secondary" size="small">
                {{ option.group }}
              </UiBadge>
              <UiBadge variant="outline" size="small">
                {{ option.status }}
              </UiBadge>
            </div>
          </div>
        </template>
      </UiAutocomplete>
    `,
  }),
  parameters: {
    docs: {
      description: {
        story:
          'Uses the `item` slot to render richer option content with metadata badges next to each result.',
      },
    },
  },
};

export const WithCheckboxes: Story = {
  render: () => ({
    components: { UiAutocomplete, UiCheckbox },
    setup() {
      const value = ref<string[]>(['apple', 'orange']);
      return { value, fruits };
    },
    template: `
      <UiAutocomplete
        v-model="value"
        multiple
        :options="fruits"
        placeholder="Search fruits"
        :show-indicator="false"
        class="w-[280px]"
      >
        <template #item="{ option, selected }">
          <div class="flex min-w-0 flex-1 items-center gap-2">
            <UiCheckbox
              name="fruit-selection"
              :model-value="selected"
              class="pointer-events-none"
              tabindex="-1"
            />
            <span class="truncate">{{ option.label }}</span>
          </div>
        </template>
      </UiAutocomplete>
    `,
  }),
  parameters: {
    docs: {
      description: {
        story:
          'Shows a checkbox-style multi-select row. The checkbox mirrors the selected state, and the default right-side check indicator is hidden.',
      },
    },
  },
};

export const WithExternalItems: Story = {
  render: () => ({
    components: { UiAutocomplete, UiAutocompleteItem },
    setup() {
      const value = ref('');
      const visibleFruits = ref(fruits);
      return { value, visibleFruits };
    },
    template: `
      <UiAutocomplete
        v-model="value"
        placeholder="Search fruit"
        start-icon="search"
        class="w-[260px]"
      >
        <UiAutocompleteItem
          v-for="fruit in visibleFruits"
          :key="fruit.value"
          :value="fruit.value"
        >
          {{ fruit.label }}
        </UiAutocompleteItem>
      </UiAutocomplete>
    `,
  }),
  parameters: {
    docs: {
      description: {
        story:
          'Renders options as external `UiAutocompleteItem` children instead of using the `options` prop. Use this when item rendering or filtering is owned by the parent.',
      },
    },
  },
};
