import useSWRSubscription from "swr/subscription"
import { filter } from "rxjs"
import type { BlockInfo } from "@polkadot-api/observable-client"
import { useUnstableProvider } from "./useUnstableProvider"

export const useBlocks = () => {
    const { chainHead$, chainId } = useUnstableProvider()
    const { data: blocks } = useSWRSubscription(
        chainHead$ && chainId && chainId ? ["blocks", chainHead$, chainId] : null,
        ([_, chainHead$, chainId], { next }) => {
            const subscription = chainHead$?.bestBlocks$
                .pipe(filter(Boolean))
                .subscribe({
                    next(blocks: BlockInfo[]) {
                        next(null, blocks)
                    },
                    error: next,
                })
            return () => subscription?.unsubscribe()
        },
    )
    return { latest: blocks?.at(0), finalized: blocks?.at(-1) }
}
