import {useState, useCallback} from 'react'

import {fn} from 'storybook/test'

import {List} from '../components/atoms/list'
import {ProductCard} from '../components/commerce/product-card'
import {ProductLink} from '../components/commerce/product-link'
import {createProduct, injectMocks} from '../mocks'

import type {Product} from '@shopify/shop-minis-platform'
import type {Meta, StoryObj} from '@storybook/react-vite'

const meta = {
  title: 'Atoms/PullToRefreshList',
  component: List as any,
  parameters: {
    layout: 'padded',
  },
  argTypes: {
    height: {
      control: 'number',
      description: 'Height of the virtualized list container',
    },
    enablePullToRefresh: {
      control: 'boolean',
      description: 'Enable pull-to-refresh functionality',
      defaultValue: true,
    },
  },
  tags: ['autodocs'],
} satisfies Meta<typeof List>

export default meta
type Story = StoryObj<typeof meta>

injectMocks()

const createProductList = (count: number) => {
  return Array.from({length: count}, (_, index) =>
    createProduct(`product-${index + 1}`, `Product ${index + 1}`, '9.99')
  )
}

const PullToRefreshListWrapper = ({
  initialItems,
  renderItem,
  ...props
}: any) => {
  const [items, setItems] = useState(initialItems)
  const [refreshing, setRefreshing] = useState(false)

  const handleRefresh = useCallback(async () => {
    setRefreshing(true)

    await new Promise(resolve => setTimeout(resolve, 2000))

    const newItems = Array.from({length: 5}, (_, index) =>
      createProduct(
        `fresh-${Date.now()}-${index}`,
        `Fresh Product ${index + 1}`,
        '12.99'
      )
    )

    setItems([...newItems, ...initialItems])
    setRefreshing(false)
  }, [initialItems])

  return (
    <List
      {...props}
      items={items}
      renderItem={renderItem}
      onRefresh={handleRefresh}
      refreshing={refreshing}
      enablePullToRefresh
    />
  )
}

const ProductLinkWithRefreshComponent = (args: any) => (
  <PullToRefreshListWrapper
    {...args}
    initialItems={createProductList(20)}
    renderItem={(product: Product) => (
      <div className="p-4">
        <ProductLink product={product} />
      </div>
    )}
  />
)

export const ProductLinkWithRefresh: Story = {
  render: ProductLinkWithRefreshComponent,
  args: {
    height: 600,
    itemSizeForRow: () => 100,
    showScrollbar: true,
  },
}

const ProductGridWithRefreshComponent = (args: any) => (
  <PullToRefreshListWrapper
    {...args}
    initialItems={createProductList(15)}
    renderItem={(product: Product) => (
      <div className="grid grid-cols-2 gap-4">
        <ProductCard product={product} onFavoriteToggled={fn()} />
        <ProductCard product={product} onFavoriteToggled={fn()} />
      </div>
    )}
  />
)

export const ProductGridWithRefresh: Story = {
  render: ProductGridWithRefreshComponent,
  args: {
    height: 600,
    itemSizeForRow: () => 220,
    showScrollbar: true,
  },
}
