import { StoryFn } from '@storybook/react';
import { expect, userEvent, within } from '@storybook/test';
import { useState } from 'react';

import DateLookup from './DateLookup';

export default {
  component: DateLookup,
  title: 'Forms/DateLookup/Tests',
};

type Story = StoryFn<typeof DateLookup>;

const Template: Story = () => {
  const [value, setValue] = useState<Date | null>(new Date(1987, 0, 10, 12, 0, 0));

  return (
    <DateLookup
      value={value}
      clearable
      placeholder="placeholder"
      onChange={(v) => {
        setValue(v);
      }}
    />
  );
};

export const ClearSpace = Template.bind({});

ClearSpace.play = async ({ canvasElement, step }) => {
  const canvas = within(canvasElement);

  await step('space can activate clear button', async () => {
    // focus on clear button
    const date = await canvas.findByText('January 10, 1987');
    await expect(date).toBeInTheDocument();
    await userEvent.tab();
    await userEvent.tab();

    // clear with space
    await userEvent.keyboard(' ');
    const placeholder = canvas.getByText('placeholder');
    await expect(placeholder).toBeInTheDocument();
  });
};

export const ClearEnter = Template.bind({});

ClearEnter.play = async ({ canvasElement, step }) => {
  const canvas = within(canvasElement);

  await step('enter can activate clear button', async () => {
    // focus on clear button
    const date = await canvas.findByText('January 10, 1987');
    await expect(date).toBeInTheDocument();
    await userEvent.tab();
    await userEvent.tab();

    // clear with space
    await userEvent.keyboard('{enter}');
    const placeholder = canvas.getByText('placeholder');
    await expect(placeholder).toBeInTheDocument();
  });
};
