import { useEffect, useRef, useState } from 'react'

import { transactionsApi, type Transaction } from '@/services/api/transactions'

const DEFAULT_BLOCK_TRANSACTION_PAGE_SIZE = 25

interface UseBlockTransactionsOptions {
  blockNumber: number
  chainId: number
  enabled: boolean
}

export function useBlockTransactions({ blockNumber, chainId, enabled }: UseBlockTransactionsOptions) {
  const [transactions, setTransactions] = useState<Transaction[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)
  const [hasNextPage, setHasNextPage] = useState(false)
  const [page, setPage] = useState(1)
  const previousBlockNumberRef = useRef(blockNumber)

  useEffect(() => {
    if (!enabled) {
      previousBlockNumberRef.current = blockNumber
      if (page !== 1) {
        setPage(1)
      }
      setTransactions([])
      setLoading(false)
      setError(false)
      setHasNextPage(false)
      return
    }

    if (previousBlockNumberRef.current !== blockNumber) {
      previousBlockNumberRef.current = blockNumber
      if (page !== 1) {
        setPage(1)
        return
      }
    }

    let cancelled = false
    setLoading(true)
    setError(false)

    void (async () => {
      const result = await transactionsApi.listByBlockSafe(
        chainId,
        blockNumber,
        page,
        DEFAULT_BLOCK_TRANSACTION_PAGE_SIZE,
      )

      if (cancelled) {
        return
      }

      setTransactions(result.items)
      setHasNextPage(result.hasNextPage)
      setError(!result.ok)
      setLoading(false)
    })()

    return () => {
      cancelled = true
    }
  }, [blockNumber, chainId, enabled, page])

  return {
    transactions,
    loading,
    error,
    hasNextPage,
    page,
    setPage,
  }
}
