'use client'

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

interface NetworkStats {
  current_block: number
  tps: number
  gps: number
  avg_gas_price: number
  pending_transactions: number
}

export default function Home() {
  const [stats, setStats] = useState<NetworkStats | null>(null)
  const [recentBlocks, setRecentBlocks] = useState<any[]>([])
  const chainId = parseInt(process.env.NEXT_PUBLIC_CHAIN_ID || '138')

  const loadStats = useCallback(async () => {
    try {
      // This would call analytics API
      // For now, placeholder
      setStats({
        current_block: 0,
        tps: 0,
        gps: 0,
        avg_gas_price: 0,
        pending_transactions: 0,
      })
    } catch (error) {
      console.error('Failed to load stats:', error)
    }
  }, [])

  const loadRecentBlocks = useCallback(async () => {
    try {
      const response = await blocksApi.list({
        chain_id: chainId,
        page: 1,
        page_size: 10,
      })
      setRecentBlocks(response.data)
    } catch (error) {
      console.error('Failed to load recent blocks:', error)
    }
  }, [chainId])

  useEffect(() => {
    loadStats()
    loadRecentBlocks()
  }, [loadStats, loadRecentBlocks])

  return (
    <main className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-4xl font-bold mb-2">SolaceScanScout</h1>
        <p className="text-lg text-gray-600 dark:text-gray-400">The Defi Oracle Meta Explorer</p>
      </div>

      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
          <Card>
            <div className="text-sm text-gray-600 dark:text-gray-400">Current Block</div>
            <div className="text-2xl font-bold">{stats.current_block.toLocaleString()}</div>
          </Card>
          <Card>
            <div className="text-sm text-gray-600 dark:text-gray-400">TPS</div>
            <div className="text-2xl font-bold">{stats.tps.toFixed(2)}</div>
          </Card>
          <Card>
            <div className="text-sm text-gray-600 dark:text-gray-400">Gas Price</div>
            <div className="text-2xl font-bold">{stats.avg_gas_price.toLocaleString()} Gwei</div>
          </Card>
          <Card>
            <div className="text-sm text-gray-600 dark:text-gray-400">Pending Tx</div>
            <div className="text-2xl font-bold">{stats.pending_transactions}</div>
          </Card>
        </div>
      )}

      <Card title="Recent Blocks">
        <div className="space-y-2">
          {recentBlocks.map((block) => (
            <div key={block.number} className="flex items-center justify-between py-2 border-b border-gray-200 dark:border-gray-700 last:border-0">
              <Link href={`/blocks/${block.number}`} className="text-primary-600 hover:underline">
                Block #{block.number}
              </Link>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                {block.transaction_count} transactions
              </div>
            </div>
          ))}
        </div>
      <div className="mt-4">
          <Link href="/blocks" className="text-primary-600 hover:underline">
            View all blocks →
          </Link>
        </div>
      </Card>

      <div className="mt-8 grid grid-cols-1 gap-4 lg:grid-cols-2">
        <Card title="Liquidity & Routes">
          <p className="text-sm leading-6 text-gray-600 dark:text-gray-400">
            Explore the public Chain 138 DODO PMM liquidity mesh, the canonical route matrix, and the
            partner payload endpoints exposed through the explorer.
          </p>
          <div className="mt-4">
            <Link href="/liquidity" className="text-primary-600 hover:underline">
              Open liquidity access →
            </Link>
          </div>
        </Card>
        <Card title="Wallet & Token Discovery">
          <p className="text-sm leading-6 text-gray-600 dark:text-gray-400">
            Add Chain 138, Ethereum Mainnet, and ALL Mainnet to MetaMask, then use the explorer token
            list URL so supported tokens appear automatically.
          </p>
          <div className="mt-4">
            <Link href="/wallet" className="text-primary-600 hover:underline">
              Open wallet tools →
            </Link>
          </div>
        </Card>
      </div>
    </main>
  )
}
