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

import { Popover, PopoverContent, PopoverTrigger } from './popover'
import { Button } from '@components/ui/button/button'

const meta = {
  title: 'Popover',
  component: PopoverContent,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
  },
  argTypes: {
    variant: {
      control: 'select',
      options: ['default', 'simple'],
    },
    align: {
      control: 'select',
      options: ['start', 'center', 'end'],
    },
    side: {
      control: 'select',
      options: ['top', 'right', 'bottom', 'left'],
    },
  },
} satisfies Meta<typeof PopoverContent>
export default meta

type Story = StoryObj<typeof meta>

export const Default: Story = {
  render: (args) => (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="outline">Open popover</Button>
      </PopoverTrigger>
      <PopoverContent className="w-[250px]" variant={args.variant} align={args.align} side={args.side}>
        <div className="bg-primary/20 p-2">popover content</div>
      </PopoverContent>
    </Popover>
  ),
  play: async () => {
    await userEvent.click(screen.getByText('Open popover'))
    const popoverContent = await screen.findByText('popover content')
    await waitFor(() => {
      expect(window.getComputedStyle(popoverContent).visibility).toBe('visible')
    })
    await userEvent.click(document.body)
    await waitFor(() => {
      expect(screen.queryByText('popover content')).toBeNull()
    })
    await userEvent.keyboard('{Escape}')
    await waitFor(() => {
      expect(screen.queryByText('popover content')).toBeNull()
    })
  },
}

export const Variants: Story = {
  render: () => (
    <div className="flex flex-wrap gap-2 items-center">
      <Popover>
        <PopoverTrigger asChild>
          <Button variant="outline">default</Button>
        </PopoverTrigger>
        <PopoverContent className="w-[250px]" variant="default">
          <div className="bg-primary/20 p-2">popover content</div>
        </PopoverContent>
      </Popover>
      <Popover>
        <PopoverTrigger asChild>
          <Button variant="outline">simple</Button>
        </PopoverTrigger>
        <PopoverContent className="w-[250px]" variant="simple">
          <div className="bg-primary/20 p-2">popover content</div>
        </PopoverContent>
      </Popover>
    </div>
  ),
}
