import { wait } from "@opensea/testing-utils/wait"
import { Meta, StoryObj } from "@storybook/react"
import { list } from "radash"
import React, { useState } from "react"
import { CenterAligned } from "../CenterAligned"
import { Spinner } from "../Spinner"
import {
  ScrollingPaginator,
  ScrollingPaginatorProps,
} from "./ScrollingPaginator"

type Story = StoryObj<typeof ScrollingPaginator>

const meta: Meta<typeof ScrollingPaginator> = {
  title: "Design System/ScrollingPaginator",
  component: ScrollingPaginator,
}

export default meta

const PAGE_SIZE = 50

const Template = (args: ScrollingPaginatorProps) => {
  const [items, setItems] = useState<number[]>(list(PAGE_SIZE - 1))
  const [isLoadingNext, setIsLoadingNext] = useState(false)

  const loadNext = async () => {
    setIsLoadingNext(true)
    await wait(500)
    setItems([...items, ...list(items.length, items.length + PAGE_SIZE - 1)])
    setIsLoadingNext(false)
  }

  return (
    <>
      {items.map(item => (
        <CenterAligned key={item}>{item}</CenterAligned>
      ))}

      <ScrollingPaginator
        {...args}
        hasNext
        isLoadingNext={isLoadingNext}
        loadNext={loadNext}
        renderFallback={() => (
          <CenterAligned className="p-4">
            <Spinner />
          </CenterAligned>
        )}
        // Needed in storybook as rootMargin doesn't apply in iframes by default
        // https://github.com/thebuilder/react-intersection-observer/blob/bc556d800d7cd322bd0eeda9b16fce0cec937233/storybook/stories/story-utils.ts#L60
        root={document as unknown as Element}
        rootMargin="180px"
      />
    </>
  )
}

export const Default: Story = {
  render: Template,
}
