//
// Copyright 2022 DXOS.org
//

import { type Meta, type StoryObj } from '@storybook/react-vite';
import React, { type PropsWithChildren, type ReactNode, useRef, useState } from 'react';

import { random } from '@dxos/random';

import { withTheme } from '../../testing';
import { Button } from '../Button';
import { Popover } from './Popover';

random.seed(1234);

const DefaultStory = ({ openTrigger, children }: PropsWithChildren<{ openTrigger: ReactNode }>) => {
  return (
    <Popover.Root defaultOpen>
      <Popover.Trigger asChild>{openTrigger}</Popover.Trigger>
      <Popover.Content>
        <Popover.Viewport>
          <p className='px-2 py-1 min-w-[18rem] max-w-[38rem]'>{children}</p>
        </Popover.Viewport>
        <Popover.Arrow />
      </Popover.Content>
    </Popover.Root>
  );
};

const meta = {
  title: 'ui/react-ui-core/components/Popover',
  component: Popover.Root,
  render: DefaultStory,
  decorators: [withTheme()],
} satisfies Meta<typeof DefaultStory>;

export default meta;

type Story = StoryObj<typeof meta>;

export const Default: Story = {
  args: {
    openTrigger: <Button>Open popover</Button>,
    children: random.lorem.paragraphs(3),
  },
};

export const VirtualTrigger = {
  render: () => {
    const [open, setOpen] = useState(true);
    const buttonRef = useRef<HTMLButtonElement | null>(null);
    return (
      <>
        <Button onClick={() => setOpen(true)} ref={buttonRef}>
          Open popover
        </Button>
        <Popover.Root open={open} onOpenChange={setOpen}>
          <Popover.VirtualTrigger virtualRef={buttonRef} />
          <Popover.Content>
            <Popover.Viewport>
              <p className='px-2 py-1 min-w-[18rem] max-w-[38rem]'>{random.lorem.paragraphs(3)}</p>
            </Popover.Viewport>
            <Popover.Arrow />
          </Popover.Content>
        </Popover.Root>
      </>
    );
  },
};
