'use client'

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

export default function BlocksPage() {
  const [blocks, setBlocks] = useState<Block[]>([])
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const chainId = parseInt(process.env.NEXT_PUBLIC_CHAIN_ID || '138')

  const loadBlocks = useCallback(async () => {
    setLoading(true)
    try {
      const response = await blocksApi.list({
        chain_id: chainId,
        page,
        page_size: 20,
        sort: 'number',
        order: 'desc',
      })
      setBlocks(response.data)
    } catch (error) {
      console.error('Failed to load blocks:', error)
    } finally {
      setLoading(false)
    }
  }, [chainId, page])

  useEffect(() => {
    loadBlocks()
  }, [loadBlocks])

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

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">Blocks</h1>

      <div className="space-y-4">
        {blocks.map((block) => (
          <Card key={block.number}>
            <div className="flex items-center justify-between">
              <div>
                <Link
                  href={`/blocks/${block.number}`}
                  className="text-lg font-semibold text-primary-600 hover:text-primary-700"
                >
                  Block #{block.number}
                </Link>
                <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                  <Address address={block.hash} truncate />
                </div>
              </div>
              <div className="text-right">
                <div className="text-sm">
                  {new Date(block.timestamp).toLocaleString()}
                </div>
                <div className="text-sm text-gray-600 dark:text-gray-400">
                  {block.transaction_count} transactions
                </div>
              </div>
            </div>
          </Card>
        ))}
      </div>

      <div className="mt-6 flex gap-4 justify-center">
        <button
          onClick={() => setPage((p) => Math.max(1, p - 1))}
          disabled={page === 1}
          className="px-4 py-2 bg-gray-200 rounded disabled:opacity-50"
        >
          Previous
        </button>
        <span className="px-4 py-2">Page {page}</span>
        <button
          onClick={() => setPage((p) => p + 1)}
          className="px-4 py-2 bg-gray-200 rounded"
        >
          Next
        </button>
      </div>
    </div>
  )
}

