import VSelect from './VSelect.vue';
import VFormField from './VFormField.vue'; // To demonstrate usage with VFormField
import type { Meta, StoryObj } from '@storybook/vue3';
import { ref } from 'vue'; // For v-model in stories

const sampleOptions = [
  { value: '', label: 'Select an option (from options prop, if placeholder not used)' , disabled: true},
  { value: 'opt1', label: 'Option 1' },
  { value: 'opt2', label: 'Option 2 (Longer Text)' },
  { value: 'opt3', label: 'Option 3', disabled: true },
  { value: 4, label: 'Option 4 (Number Value)' }, // Example with number value
  { value: 'opt5', label: 'Option 5' },
];

const meta: Meta<typeof VSelect> = {
  title: 'Valerie/VSelect',
  component: VSelect,
  tags: ['autodocs'],
  argTypes: {
    modelValue: { control: 'select', options: ['', 'opt1', 'opt2', 4, 'opt5'], description: 'Bound value using v-model. Control shows possible values from sampleOptions.' },
    options: { control: 'object' },
    disabled: { control: 'boolean' },
    required: { control: 'boolean' },
    error: { control: 'boolean', description: 'Applies error styling.' },
    id: { control: 'text' },
    placeholder: { control: 'text' },
    // 'update:modelValue': { action: 'updated' }
  },
  parameters: {
    docs: {
      description: {
        component: 'A select component for choosing from a list of options, supporting v-model, states, and placeholder.',
      },
    },
  },
};

export default meta;
type Story = StoryObj<typeof VSelect>;

// Template for v-model interaction in stories
const VModelTemplate: Story = {
  render: (args) => ({
    components: { VSelect },
    setup() {
      // Storybook's args are reactive. For v-model, ensure the control updates the arg.
      // If direct v-model="args.modelValue" has issues, a local ref can be used.
      const storyValue = ref(args.modelValue); // Initialize with current arg value
      const onChange = (newValue: string | number) => {
        storyValue.value = newValue; // Update local ref
        // args.modelValue = newValue; // This would update the arg if mutable, SB controls should handle this
      }
      // Watch for external changes to modelValue from Storybook controls
      watch(() => args.modelValue, (newVal) => {
        storyValue.value = newVal;
      });
      return { args, storyValue, onChange };
    },
    template: '<VSelect v-bind="args" :modelValue="storyValue" @update:modelValue="onChange" />',
  }),
};

export const Basic: Story = {
  ...VModelTemplate,
  args: {
    id: 'basicSelect',
    options: sampleOptions.filter(opt => !opt.disabled || opt.value === ''), // Filter out pre-disabled for basic
    modelValue: 'opt1',
  },
};

export const WithPlaceholder: Story = {
  ...VModelTemplate,
  args: {
    id: 'placeholderSelect',
    options: sampleOptions.filter(opt => opt.value !== ''), // Remove the empty value option from main list if placeholder is used
    modelValue: '', // Placeholder should be selected
    placeholder: 'Please choose an item...',
  },
};

export const Disabled: Story = {
  ...VModelTemplate,
  args: {
    id: 'disabledSelect',
    options: sampleOptions,
    modelValue: 'opt2',
    disabled: true,
  },
};

export const Required: Story = {
  ...VModelTemplate,
  args: {
    id: 'requiredSelect',
    options: sampleOptions.filter(opt => opt.value !== ''),
    modelValue: '', // Start with nothing selected if required and placeholder exists
    placeholder: 'You must select one',
    required: true,
  },
   parameters: {
    docs: {
      description: { story: 'The `required` attribute is set. If a placeholder is present and selected, form validation may fail as expected.' },
    },
  },
};

export const ErrorState: Story = {
  ...VModelTemplate,
  args: {
    id: 'errorSelect',
    options: sampleOptions,
    modelValue: 'opt1',
    error: true,
  },
};

export const WithDisabledOptions: Story = {
  ...VModelTemplate,
  args: {
    id: 'disabledOptionsSelect',
    options: sampleOptions, // sampleOptions already includes a disabled option (opt3)
    modelValue: 'opt1',
  },
};

export const NumberValueSelected: Story = {
  ...VModelTemplate,
  args: {
    id: 'numberValueSelect',
    options: sampleOptions,
    modelValue: 4, // Corresponds to 'Option 4 (Number Value)'
  },
};


// Story demonstrating VSelect used within VFormField
export const InFormField: Story = {
  render: (args) => ({
    components: { VSelect, VFormField },
    setup() {
      const storyValue = ref(args.selectArgs.modelValue);
       watch(() => args.selectArgs.modelValue, (newVal) => {
        storyValue.value = newVal;
      });
      const onChange = (newValue: string | number) => {
        storyValue.value = newValue;
      }
      return { args, storyValue, onChange };
    },
    template: `
      <VFormField :label="args.formFieldArgs.label" :forId="args.selectArgs.id" :errorMessage="args.formFieldArgs.errorMessage">
        <VSelect
          v-bind="args.selectArgs"
          :modelValue="storyValue"
          @update:modelValue="onChange"
        />
      </VFormField>
    `,
  }),
  args: {
    formFieldArgs: {
      label: 'Choose Category',
      errorMessage: '',
    },
    selectArgs: {
      id: 'categorySelect',
      options: sampleOptions.filter(opt => opt.value !== ''),
      modelValue: '',
      placeholder: 'Select a category...',
      error: false,
    },
  },
   parameters: {
    docs: {
      description: { story: '`VSelect` used inside a `VFormField`. The `id` on `VSelect` should match `forId` on `VFormField`.' },
    },
  },
};

export const InFormFieldWithError: Story = {
  ...InFormField, // Inherit render function
  args: {
    formFieldArgs: {
      label: 'Select Priority',
      errorMessage: 'A priority must be selected.',
    },
    selectArgs: {
      id: 'prioritySelectError',
      options: sampleOptions.filter(opt => opt.value !== ''),
      modelValue: '', // Nothing selected, causing error
      placeholder: 'Choose priority...',
      error: true, // Set VSelect's error state
      required: true,
    },
  },
};
