import { useState } from 'react';
import { StoryObj } from '@storybook/react-webpack5';
import { userEvent, within } from 'storybook/test';
import { createSandboxStory, globalScope } from '../../.storybook/components/sandbox/SandboxEditor';
import Calendar, { type CalendarProps } from './Calendar';
import Modal from '../modal';
import Button from '../button';

/** Inline calendar for selecting a single date, with optional min/max bounds. */
export default {
  component: Calendar,
  title: 'Forms/Calendar',
  argTypes: {
    monthFormat: { control: 'select', options: ['long', 'short'] },
    min: { control: 'date' },
    max: { control: 'date' },
  },
};

type Story = StoryObj<typeof Calendar>;

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 Sandbox = createSandboxStory({
  code: `const App = () => {
  const [value, setValue] = React.useState(new Date('2024-06-15'));

  return (
    <Calendar
      monthFormat="long"
      value={value}
      onChange={(date) => setValue(date)}
    />
  );
};`,
  scope: { ...globalScope, Calendar },
});

export const Basic: Story = {
  render: (args: CalendarProps) => {
    const [value, setValue] = useState<Date | null>(epoch);
    return (
      <Calendar
        {...args}
        min={args.min ? new Date(args.min) : thePast}
        max={args.max ? new Date(args.max) : theFuture}
        value={value}
        onChange={(v) => setValue(v)}
      />
    );
  },
  args: {
    monthFormat: 'long',
    min: thePast,
    max: theFuture,
  },
};

export const WithoutConstraints: Story = {
  render: () => {
    const [value, setValue] = useState<Date | null>(epoch);
    return <Calendar value={value} onChange={(v) => setValue(v)} />;
  },
};

export const NullValue: Story = {
  render: () => {
    const [value, setValue] = useState<Date | null>(null);
    return <Calendar value={value} min={thePast} max={theFuture} onChange={(v) => setValue(v)} />;
  },
};

export const InsideModal: Story = {
  render: () => {
    const [open, setOpen] = useState(false);
    const [value, setValue] = useState<Date | null>(epoch);
    return (
      <>
        <Button size="sm" v2 type="button" onClick={() => setOpen(true)}>
          Open modal
        </Button>
        <Modal
          open={open}
          title="Select a date"
          body={
            <Calendar value={value} min={thePast} max={theFuture} onChange={(v) => setValue(v)} />
          }
          onClose={() => setOpen(false)}
        />
      </>
    );
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
  },
};
