import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect, userEvent, screen } from 'storybook/test'
import { useState } from 'react'
import { Slider } from './slider'

const meta = {
  title: 'Slider',
  component: Slider,
  parameters: {
    layout: 'centered',
  },
  tags: ['autodocs'],
  argTypes: {
    min: { control: 'number' },
    max: { control: 'number' },
    step: { control: 'number' },
    defaultValue: { control: 'object' },
    sliderVariant: {
      control: 'select',
      options: ['default', 'gray'],
    },
    knobVariant: {
      control: 'select',
      options: ['default', 'gray'],
    },
  },
  args: {
    min: 0,
    max: 100,
    step: 1,
    defaultValue: [25],
    sliderVariant: 'default',
    knobVariant: 'default',
  },
} satisfies Meta<typeof Slider>

export default meta

type Story = StoryObj<typeof meta>

export const Default: Story = {
  args: {
    defaultValue: [25],
    className: 'w-64',
  },
}

export const Variants: Story = {
  render: () => {
    return (
      <div className="space-y-4">
        <div className="flex flex-col items-center space-y-2">
          <Slider defaultValue={[25]} className="w-64" />
          <span>Default</span>
        </div>
        <div className="flex flex-col items-center space-y-2">
          <Slider defaultValue={[25, 75]} className="w-64" />
          <span>Range</span>
        </div>
        <div className="flex flex-col items-center space-y-2">
          <Slider defaultValue={[25]} sliderVariant="gray" className="w-64" />
          <span>Gray Slider</span>
        </div>
        <div className="flex flex-col items-center space-y-2">
          <Slider defaultValue={[25]} knobVariant="gray" className="w-64" />
          <span>Gray Knob</span>
        </div>
        <div className="flex flex-col items-center space-y-2">
          <Slider defaultValue={[25]} sliderVariant="gray" knobVariant="gray" className="w-64" />
          <span>Gray Both</span>
        </div>
      </div>
    )
  },
}

export const InteractiveTest: Story = {
  render: () => {
    const [value, setValue] = useState<number[]>([30])
    return (
      <div className="space-y-4">
        <Slider value={value} onValueChange={setValue} className="w-64" data-testid="controlled-slider" />
        <p data-testid="slider-value">Value: {value}</p>
      </div>
    )
  },
  play: async () => {
    // Find the slider
    const slider = screen.getByTestId('controlled-slider')
    const valueText = screen.getByTestId('slider-value')

    // Get the thumb and track to simulate interactions
    const thumb = slider.querySelector('[data-orientation]')

    // Click on a different position on the slider
    await userEvent.click(screen.getByTestId('controlled-slider'))

    // Check if the value updates (approximate check)
    await expect(valueText.textContent).toBe('Value: 0')
  },
}
