"use client"
import React, { memo, useCallback, useState } from "react"
import { CenterAligned } from "../CenterAligned"
import { RetryButton } from "../RetryButton"
import {
  UseScrollingPaginationOptions,
  useScrollingPagination,
} from "./useScrollingPagination"

export type ScrollingPaginatorProps = {
  renderFallback?: React.ComponentType
  element?: string
  hasError?: boolean
} & UseScrollingPaginationOptions

export const ScrollingPaginator = memo(function ScrollingPaginator({
  renderFallback: Fallback,
  hasNext,
  loadNext,
  isLoadingNext,
  hasError: hasErrorProp,
}: ScrollingPaginatorProps) {
  const [hasLocalError, setHasLocalError] = useState(false)

  const hasError = hasErrorProp || hasLocalError

  const onError = useCallback(() => {
    setHasLocalError(true)
  }, [])

  const { ref, isLoading } = useScrollingPagination({
    hasNext: hasNext && !hasLocalError,
    loadNext,
    isLoadingNext,
    onError,
  })

  const renderContent = () => {
    if (hasError || hasErrorProp) {
      return (
        <CenterAligned className="my-4">
          <RetryButton
            onClick={async () => {
              await loadNext()
              setHasLocalError(false)
            }}
          />
        </CenterAligned>
      )
    }

    if (!isLoading) {
      return <div style={{ height: "1px" }} />
    }

    if (Fallback) {
      return <Fallback />
    }

    return null
  }

  return <div ref={ref}>{renderContent()}</div>
})
