import { useState } from 'react';
import { userEvent } from 'storybook/test';
import { Field } from '..';
import { Size } from '../common';
import { storyConfig } from '../test-utils';
import DateLookup, { type DateLookupProps } from './DateLookup';

export default {
  component: DateLookup,
  title: 'Forms/DateLookup',
  argTypes: {
    size: { control: 'select', options: [Size.SMALL, Size.MEDIUM, Size.LARGE] },
    disabled: { control: 'boolean' },
    label: { control: 'text' },
    monthFormat: { control: 'select', options: ['long', 'short'] },
    placeholder: { control: 'text' },
    id: { control: 'text' },
    clearable: { control: 'boolean' },
    min: { control: 'date' },
    max: { control: 'date' },
  },
};

const epoch = new Date('2011-01-01');
const theFuture = new Date(epoch);
theFuture.setUTCDate(epoch.getUTCDate() + 10);
const thePast = new Date(epoch);
thePast.setUTCDate(epoch.getUTCDate() - 10);

export const Basic = (args: DateLookupProps) => {
  const [value, setValue] = useState<Date | null>(epoch);
  return (
    <DateLookup
      {...args}
      min={args.min ? new Date(args.min) : thePast}
      max={args.max ? new Date(args.max) : theFuture}
      value={value}
      onChange={(v) => setValue(v)}
    />
  );
};
Basic.args = {
  size: Size.MEDIUM,
  disabled: false,
  label: 'label',
  monthFormat: 'long',
  placeholder: 'placeholder',
  id: 'date-lookup',
  clearable: true,
  min: thePast,
  max: theFuture,
};
Basic.play = async ({ canvasElement }: { canvasElement: HTMLElement }) => {
  await userEvent.tab();
  await userEvent.keyboard(' ');
};

export const Basic400Zoom = storyConfig(
  {
    render: Basic,
    play: Basic.play,
    parameters: { chromatic: { delay: 2000 } },
  },
  { variants: ['400%'] },
);

export const WithField = (args: DateLookupProps) => {
  const [value, setValue] = useState<Date | null>(epoch);
  return (
    <Field label="Date lookup">
      <DateLookup
        {...args}
        min={args.min ? new Date(args.min) : thePast}
        max={args.max ? new Date(args.max) : theFuture}
        value={value}
        onChange={(v) => setValue(v)}
      />
    </Field>
  );
};

export const RightAligned = (args: DateLookupProps) => {
  const [value, setValue] = useState<Date | null>(epoch);
  return (
    <div className="row">
      <div className="col-xs-6">
        <p>
          This example demonstrates the automatic right alignment behaviour of the calendar. If,
          when the calendar is opened, it is cut off on the right, the component will align the
          calendar to the rightmost edge of the lookup input.
        </p>
      </div>
      <div className="col-xs-6">
        <DateLookup
          {...args}
          id="right-aligned"
          min={args.min ? new Date(args.min) : thePast}
          max={args.max ? new Date(args.max) : theFuture}
          value={value}
          onChange={(v) => setValue(v)}
        />
      </div>
    </div>
  );
};
