'use client'

import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import { blocksApi, Block } from '@/services/api/blocks'
import { Card, Address } from '@/libs/frontend-ui-primitives'
import Link from 'next/link'

export default function BlockDetailPage() {
  const router = useRouter()
  const rawNumber = typeof router.query.number === 'string' ? router.query.number : ''
  const blockNumber = parseInt(rawNumber, 10)
  const isValidBlock = rawNumber !== '' && !Number.isNaN(blockNumber) && blockNumber >= 0
  const chainId = parseInt(process.env.NEXT_PUBLIC_CHAIN_ID || '138')

  const [block, setBlock] = useState<Block | null>(null)
  const [loading, setLoading] = useState(true)

  const loadBlock = useCallback(async () => {
    setLoading(true)
    try {
      const response = await blocksApi.getByNumber(chainId, blockNumber)
      setBlock(response.data)
    } catch (error) {
      console.error('Failed to load block:', error)
    } finally {
      setLoading(false)
    }
  }, [chainId, blockNumber])

  useEffect(() => {
    if (!router.isReady) {
      return
    }
    if (!isValidBlock) {
      setLoading(false)
      setBlock(null)
      return
    }
    loadBlock()
  }, [isValidBlock, loadBlock, router.isReady])

  if (!router.isReady) {
    return <div className="p-8">Loading block...</div>
  }

  if (!isValidBlock) {
    return <div className="p-8">Invalid block number. Please use a valid block number from the URL.</div>
  }

  if (loading) {
    return <div className="p-8">Loading block...</div>
  }

  if (!block) {
    return <div className="p-8">Block not found</div>
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">Block #{block.number}</h1>

      <div className="mb-6 flex flex-wrap gap-3 text-sm">
        <Link href="/blocks" className="text-primary-600 hover:underline">
          Back to blocks
        </Link>
        {block.number > 0 ? (
          <Link href={`/blocks/${block.number - 1}`} className="text-primary-600 hover:underline">
            Previous block
          </Link>
        ) : null}
        <Link href={`/blocks/${block.number + 1}`} className="text-primary-600 hover:underline">
          Next block
        </Link>
      </div>

      <Card title="Block Information">
        <div className="space-y-4">
          <div>
            <span className="font-semibold">Hash:</span>
            <Address address={block.hash} className="ml-2" />
          </div>
          <div>
            <span className="font-semibold">Timestamp:</span>
            <span className="ml-2">{new Date(block.timestamp).toLocaleString()}</span>
          </div>
          <div>
            <span className="font-semibold">Miner:</span>
            <Link href={`/addresses/${block.miner}`} className="ml-2 text-primary-600 hover:underline">
              <Address address={block.miner} truncate />
            </Link>
          </div>
          <div>
            <span className="font-semibold">Transactions:</span>
            <Link href="/transactions" className="ml-2 text-primary-600 hover:underline">
              {block.transaction_count}
            </Link>
          </div>
          <div>
            <span className="font-semibold">Gas Used:</span>
            <span className="ml-2">{block.gas_used.toLocaleString()} / {block.gas_limit.toLocaleString()}</span>
          </div>
        </div>
      </Card>
    </div>
  )
}
