'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/router'
import { Card, Address, Table } from '@/libs/frontend-ui-primitives'
import Link from 'next/link'
import {
  transactionsApi,
  Transaction,
  TransactionInternalCall,
  TransactionLookupDiagnostic,
  TransactionTokenTransfer,
} from '@/services/api/transactions'
import { formatTimestamp, formatTokenAmount, formatWeiAsEth } from '@/utils/format'
import { DetailRow } from '@/components/common/DetailRow'
import EntityBadge from '@/components/common/EntityBadge'
import PageIntro from '@/components/common/PageIntro'
import PaginationControls from '@/components/common/PaginationControls'
import SectionTabs, { type SectionTab } from '@/components/common/SectionTabs'
import { getGruCatalogPosture } from '@/services/api/gruCatalog'
import { assessTransactionCompliance } from '@/utils/transactionCompliance'
import {
  tokenAggregationApi,
  type CheckpointTxAttestationSnapshot,
  type TokenAggregationHistoricalPriceSnapshot,
} from '@/services/api/tokenAggregation'
import { estimateNativeUsdValue, estimateTokenUsdValue, getNativeAssetDescriptor, getNativeAssetPriceAtSafe } from '@/services/api/nativeAssetPricing'

function isValidTransactionHash(value: string) {
  return /^0x[a-fA-F0-9]{64}$/.test(value)
}

function formatUsd(value: string | number | undefined): string {
  if (value == null) return 'Unavailable'
  const numeric = typeof value === 'number' ? value : Number(value)
  if (!Number.isFinite(numeric)) return 'Unavailable'
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: numeric >= 100 ? 0 : 2,
  }).format(numeric)
}

function formatHistoricalPriceSource(source: string | undefined): string {
  switch (source) {
    case 'ohlcv_5m':
      return 'historical OHLCV 5m'
    case 'ohlcv_15m':
      return 'historical OHLCV 15m'
    case 'ohlcv_1h':
      return 'historical OHLCV 1h'
    case 'ohlcv_4h':
      return 'historical OHLCV 4h'
    case 'ohlcv_24h':
      return 'historical OHLCV 24h'
    case 'coingecko_history':
      return 'historical CoinGecko market'
    case 'current_market_fallback':
      return 'current market fallback'
    case 'canonical_fallback':
      return 'canonical fallback'
    default:
      return 'unavailable'
  }
}

export default function TransactionDetailPage() {
  const router = useRouter()
  const hash = typeof router.query.hash === 'string' ? router.query.hash : ''
  const isValidHash = hash !== '' && isValidTransactionHash(hash)
  const chainId = parseInt(process.env.NEXT_PUBLIC_CHAIN_ID || '138')

  const [transaction, setTransaction] = useState<Transaction | null>(null)
  const [internalCalls, setInternalCalls] = useState<TransactionInternalCall[]>([])
  const [diagnostic, setDiagnostic] = useState<TransactionLookupDiagnostic | null>(null)
  const [historicalTokenPrices, setHistoricalTokenPrices] = useState<Record<string, TokenAggregationHistoricalPriceSnapshot>>({})
  const [historicalNativePrice, setHistoricalNativePrice] = useState<TokenAggregationHistoricalPriceSnapshot | null>(null)
  const [checkpointAttestation, setCheckpointAttestation] = useState<CheckpointTxAttestationSnapshot | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<'evidence' | 'details' | 'transfers' | 'internal' | 'raw'>('evidence')
  const [transferPage, setTransferPage] = useState(1)
  const [internalPage, setInternalPage] = useState(1)
  const pageSize = 8

  const loadTransaction = useCallback(async () => {
    setLoading(true)
    try {
      const [{ ok, data }, internalResult] = await Promise.all([
        transactionsApi.getSafe(chainId, hash),
        transactionsApi.getInternalTransactionsSafe(hash),
      ])
      if (!ok) {
        setTransaction(null)
        setInternalCalls([])
        setDiagnostic(await transactionsApi.diagnoseMissing(chainId, hash))
        return
      }
      setTransaction(data ?? null)
      setInternalCalls(internalResult.ok ? internalResult.data : [])
      setDiagnostic(null)
    } catch (error) {
      console.error('Failed to load transaction:', error)
      setTransaction(null)
      setInternalCalls([])
      setDiagnostic(await transactionsApi.diagnoseMissing(chainId, hash))
    } finally {
      setLoading(false)
    }
  }, [chainId, hash])

  const transactionNotFoundMessage = (() => {
    if (!diagnostic) {
      return 'Transaction not found.'
    }

    if (diagnostic.rpc_transaction_found && !diagnostic.rpc_receipt_found) {
      return 'This hash was found on the Chain 138 public RPC, but it does not have a mined receipt yet and Blockscout has not indexed it.'
    }

    if (diagnostic.rpc_transaction_found && diagnostic.rpc_receipt_found && !diagnostic.explorer_indexed) {
      return 'This hash exists on Chain 138, but Blockscout has not indexed it yet.'
    }

    return 'This hash was not found in Blockscout or in the Chain 138 public RPC, which usually means it belongs to a different network, was replaced, or never broadcast successfully.'
  })()

  useEffect(() => {
    if (!router.isReady || !hash) {
      setLoading(router.isReady ? false : true)
      if (router.isReady && !hash) {
        setTransaction(null)
      }
      return
    }
    if (!isValidHash) {
      setLoading(false)
      setTransaction(null)
      return
    }
    loadTransaction()
  }, [hash, isValidHash, loadTransaction, router.isReady])

  useEffect(() => {
    let active = true

    const tokenAddresses = (transaction?.token_transfers || [])
      .map((transfer) => transfer.token_address)
      .filter((candidate, index, values): candidate is string => typeof candidate === 'string' && candidate.trim().length > 0 && values.indexOf(candidate) === index)

    if (!transaction?.created_at || tokenAddresses.length === 0) {
      setHistoricalTokenPrices({})
      return () => {
        active = false
      }
    }

    Promise.all(tokenAddresses.map((address) => tokenAggregationApi.getPriceAtSafe(chainId, address, transaction.created_at))).then((results) => {
      if (!active) return
      const snapshots = results
        .filter((result): result is { ok: true; data: TokenAggregationHistoricalPriceSnapshot | null } => result.ok)
        .map((result) => result.data)
        .filter((snapshot): snapshot is TokenAggregationHistoricalPriceSnapshot => Boolean(snapshot?.tokenAddress))
      setHistoricalTokenPrices(Object.fromEntries(snapshots.map((snapshot) => [snapshot.tokenAddress.toLowerCase(), snapshot])))
    }).catch(() => {
      if (active) {
        setHistoricalTokenPrices({})
      }
    })

    return () => {
      active = false
    }
  }, [chainId, transaction?.created_at, transaction?.token_transfers])

  useEffect(() => {
    let active = true

    if (!transaction?.created_at) {
      setHistoricalNativePrice(null)
      return () => {
        active = false
      }
    }

    getNativeAssetPriceAtSafe(chainId, transaction.created_at).then(({ data }) => {
      if (!active) return
      setHistoricalNativePrice(data)
    }).catch(() => {
      if (active) {
        setHistoricalNativePrice(null)
      }
    })

    return () => {
      active = false
    }
  }, [chainId, transaction?.created_at])

  useEffect(() => {
    let active = true
    if (!isValidHash) {
      setCheckpointAttestation(null)
      return () => {
        active = false
      }
    }
    tokenAggregationApi.getCheckpointAttestationSafe(hash).then(({ ok, data }) => {
      if (!active) return
      setCheckpointAttestation(ok && data?.included ? data : null)
    }).catch(() => {
      if (active) setCheckpointAttestation(null)
    })
    return () => {
      active = false
    }
  }, [hash, isValidHash])

  const tokenTransferColumns = [
    {
      header: 'Token',
      accessor: (transfer: TransactionTokenTransfer) => {
        const gruPosture = getGruCatalogPosture({
          symbol: transfer.token_symbol,
          address: transfer.token_address,
        })
        return (
        <div className="space-y-1">
          <div className="flex flex-wrap items-center gap-2">
            <div className="font-medium text-gray-900 dark:text-white">{transfer.token_symbol || transfer.token_name || 'Token'}</div>
            {gruPosture?.isGru ? <EntityBadge label="GRU" tone="success" /> : null}
            {gruPosture?.isX402Ready ? <EntityBadge label="x402 ready" tone="info" /> : null}
            {gruPosture?.isWrappedTransport ? <EntityBadge label="wrapped" tone="warning" /> : null}
          </div>
          {transfer.token_address && (
            <Link href={`/tokens/${transfer.token_address}`} className="text-primary-600 hover:underline">
              <Address address={transfer.token_address} truncate showCopy={false} />
            </Link>
          )}
        </div>
      )},
    },
    {
      header: 'From',
      accessor: (transfer: TransactionTokenTransfer) => (
        <Link href={`/addresses/${transfer.from_address}`} className="text-primary-600 hover:underline">
          {transfer.from_label || <Address address={transfer.from_address} truncate showCopy={false} />}
        </Link>
      ),
    },
    {
      header: 'To',
      accessor: (transfer: TransactionTokenTransfer) => (
        <Link href={`/addresses/${transfer.to_address}`} className="text-primary-600 hover:underline">
          {transfer.to_label || <Address address={transfer.to_address} truncate showCopy={false} />}
        </Link>
      ),
    },
    {
      header: 'Amount',
      accessor: (transfer: TransactionTokenTransfer) => (
        formatTokenAmount(transfer.amount, transfer.token_decimals, transfer.token_symbol)
      ),
    },
    {
      header: 'Transfer-Time Value',
      accessor: (transfer: TransactionTokenTransfer) => {
        const want = transfer.token_address.toLowerCase()
        const checkpointLine = checkpointAttestation?.leaf?.transfers?.find((line) => {
          const addr = (line.tokenAddress || line.token || '').toLowerCase()
          return addr === want
        })
        const historicalPrice = historicalTokenPrices[transfer.token_address.toLowerCase()]
        const totalUsd = checkpointLine?.valueUsd != null
          ? Number(checkpointLine.valueUsd)
          : estimateTokenUsdValue(transfer.amount, transfer.token_decimals, historicalPrice?.priceUsd)
        const priceSource = checkpointLine?.priceSource ?? historicalPrice?.source
        return (
          <div className="space-y-1 text-sm">
            <div>{totalUsd != null && Number.isFinite(totalUsd) ? formatUsd(totalUsd) : 'Unavailable'}</div>
            <div className="text-xs text-gray-500 dark:text-gray-400">
              Unit price: {checkpointLine?.valueUsd != null ? 'checkpoint leaf' : formatUsd(historicalPrice?.priceUsd)}
            </div>
            <div className="text-xs text-gray-500 dark:text-gray-400">
              Source: {checkpointLine ? `checkpoint (${priceSource || 'enriched'})` : formatHistoricalPriceSource(priceSource)}
            </div>
          </div>
        )
      },
    },
  ]

  const internalCallColumns = [
    {
      header: 'Type',
      accessor: (call: TransactionInternalCall) => call.type || 'call',
    },
    {
      header: 'From',
      accessor: (call: TransactionInternalCall) => (
        <Link href={`/addresses/${call.from_address}`} className="text-primary-600 hover:underline">
          {call.from_label || <Address address={call.from_address} truncate showCopy={false} />}
        </Link>
      ),
    },
    {
      header: 'To',
      accessor: (call: TransactionInternalCall) => {
        const targetAddress = call.contract_address || call.to_address
        const targetLabel = call.contract_label || call.to_label
        if (!targetAddress) {
          return <span className="text-gray-500">Unknown</span>
        }
        return (
          <Link href={`/addresses/${targetAddress}`} className="text-primary-600 hover:underline">
            {targetLabel || <Address address={targetAddress} truncate showCopy={false} />}
          </Link>
        )
      },
    },
    {
      header: 'Value',
      accessor: (call: TransactionInternalCall) => formatWeiAsEth(call.value),
    },
    {
      header: 'Status',
      accessor: (call: TransactionInternalCall) => (
        <span className={call.success === false ? 'text-red-600' : 'text-green-600'}>
          {call.success === false ? (call.error || 'Failed') : 'Success'}
        </span>
      ),
    },
  ]

  const gasUtilization = transaction?.gas_used != null && transaction.gas_limit > 0
    ? Math.round((transaction.gas_used / transaction.gas_limit) * 100)
    : null
  const tokenTransferCount = transaction?.token_transfers?.length || 0
  const internalCallCount = internalCalls.length
  const nativeAssetSymbol = getNativeAssetDescriptor(chainId).symbol
  const checkpointLeaf = checkpointAttestation?.leaf
  const checkpointNativeUsd = checkpointLeaf?.nativeValueUsd ?? checkpointLeaf?.valueUsd
  const parsedCheckpointNativeUsd = checkpointNativeUsd != null ? Number(checkpointNativeUsd) : null
  const nativeValueUsd = parsedCheckpointNativeUsd != null && Number.isFinite(parsedCheckpointNativeUsd)
    ? parsedCheckpointNativeUsd
    : estimateNativeUsdValue(transaction?.value, historicalNativePrice?.priceUsd)
  const nativeFeeUsd = estimateNativeUsdValue(transaction?.fee, historicalNativePrice?.priceUsd)
  const checkpointTotalUsd = checkpointLeaf?.totalTransfersUsd ?? checkpointLeaf?.valueUsd
  const complianceAssessment = transaction
    ? assessTransactionCompliance({
        transaction,
        internalCalls,
        tokenTransfers: transaction.token_transfers || [],
      })
    : null
  const tabs: SectionTab<typeof activeTab>[] = [
    { id: 'evidence', label: 'Evidence' },
    { id: 'details', label: 'Details' },
    { id: 'transfers', label: 'Transfers', count: tokenTransferCount },
    { id: 'internal', label: 'Internal', count: internalCallCount },
    ...(transaction?.input_data ? [{ id: 'raw' as const, label: 'Raw input' }] : []),
  ]
  const transferPageCount = Math.max(1, Math.ceil((transaction?.token_transfers?.length || 0) / pageSize))
  const internalPageCount = Math.max(1, Math.ceil(internalCalls.length / pageSize))
  const pagedTokenTransfers = useMemo(
    () => (transaction?.token_transfers || []).slice((transferPage - 1) * pageSize, transferPage * pageSize),
    [transaction?.token_transfers, transferPage],
  )
  const pagedInternalCalls = useMemo(
    () => internalCalls.slice((internalPage - 1) * pageSize, internalPage * pageSize),
    [internalCalls, internalPage],
  )

  useEffect(() => {
    setActiveTab('evidence')
    setTransferPage(1)
    setInternalPage(1)
  }, [hash])

  return (
    <div className="container mx-auto px-4 py-6 sm:py-8">
      <PageIntro
        eyebrow="Transaction Detail"
        title="Transaction"
        description="Inspect a single transaction and pivot into its block, counterparties, or a broader explorer search when you need more context."
        actions={[
          { href: '/transactions', label: 'All transactions' },
          { href: '/blocks', label: 'Recent blocks' },
          { href: '/search', label: 'Search explorer' },
        ]}
      />

      <div className="mb-6 flex flex-wrap gap-3 text-sm">
        <Link href="/transactions" className="text-primary-600 hover:underline">
          Back to transactions
        </Link>
        {(transaction?.hash || hash) && (
          <Link href={`/search?q=${encodeURIComponent(transaction?.hash || hash)}`} className="text-primary-600 hover:underline">
            Search this hash
          </Link>
        )}
      </div>

      {!router.isReady || loading ? (
        <Card>
          <p className="text-sm text-gray-600 dark:text-gray-400">Loading transaction...</p>
        </Card>
      ) : !isValidHash ? (
        <Card>
          <p className="text-sm text-gray-600 dark:text-gray-400">Invalid transaction hash. Please use a full 66-character 0x-prefixed hash.</p>
          <div className="mt-4 flex flex-wrap gap-3 text-sm">
            <Link href="/transactions" className="text-primary-600 hover:underline">
              Back to transactions →
            </Link>
            <Link href="/search" className="text-primary-600 hover:underline">
              Search the explorer →
            </Link>
          </div>
        </Card>
      ) : !transaction ? (
        <Card>
          <p className="text-sm text-gray-600 dark:text-gray-400">{transactionNotFoundMessage}</p>
          {diagnostic && (
            <dl className="mt-4 space-y-2 text-sm text-gray-600 dark:text-gray-400">
              <DetailRow label="Checked hash">{diagnostic.checked_hash}</DetailRow>
              {diagnostic.latest_block_number != null && (
                <DetailRow label="Latest Chain 138 block">#{diagnostic.latest_block_number}</DetailRow>
              )}
              <DetailRow label="Blockscout indexed">{diagnostic.explorer_indexed ? 'Yes' : 'No'}</DetailRow>
              <DetailRow label="Public RPC transaction">{diagnostic.rpc_transaction_found ? 'Yes' : 'No'}</DetailRow>
              <DetailRow label="Public RPC receipt">{diagnostic.rpc_receipt_found ? 'Yes' : 'No'}</DetailRow>
            </dl>
          )}
          <div className="mt-4 flex flex-wrap gap-3 text-sm">
            <Link href="/transactions" className="text-primary-600 hover:underline">
              Browse recent transactions →
            </Link>
            <Link href="/search" className="text-primary-600 hover:underline">
              Search the explorer →
            </Link>
          </div>
        </Card>
      ) : (
        <div className="space-y-6">
          <Card title="Execution Summary">
            <div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-4">
              <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
                <div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Outcome</div>
                <div className="mt-3 flex flex-wrap gap-2">
                  <EntityBadge
                    label={transaction.status === 1 ? 'success' : 'failed'}
                    tone={transaction.status === 1 ? 'success' : 'warning'}
                  />
                  {transaction.contract_address ? <EntityBadge label="contract creation" tone="warning" /> : null}
                  {transaction.method ? <EntityBadge label={transaction.method} tone="info" /> : null}
                </div>
              </div>
              <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
                <div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Gas & Fees</div>
                <div className="mt-3 space-y-2 text-sm text-gray-700 dark:text-gray-300">
                  <div>
                    Fee: {transaction.fee ? formatWeiAsEth(transaction.fee) : 'Unavailable'}
                    {nativeFeeUsd != null ? ` (${formatUsd(nativeFeeUsd)})` : ''}
                  </div>
                  <div>Gas used: {transaction.gas_used != null ? transaction.gas_used.toLocaleString() : 'Unavailable'}</div>
                  <div>Utilization: {gasUtilization != null ? `${gasUtilization}%` : 'Unavailable'}</div>
                </div>
              </div>
              <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
                <div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Value Movement</div>
                <div className="mt-3 space-y-2 text-sm text-gray-700 dark:text-gray-300">
                  <div>
                    Native value: {formatWeiAsEth(transaction.value)}
                    {nativeValueUsd != null ? ` (${formatUsd(nativeValueUsd)})` : ''}
                  </div>
                  <div>Transfer-time native price: {historicalNativePrice?.priceUsd != null ? `${formatUsd(historicalNativePrice.priceUsd)} per ${nativeAssetSymbol}` : 'Unavailable'}</div>
                  <div>Pricing source: {checkpointLeaf ? `checkpoint mirror (${checkpointLeaf.priceSource || 'enriched'})` : formatHistoricalPriceSource(historicalNativePrice?.source)}</div>
                  {checkpointAttestation ? (
                    <div>
                      Checkpoint batch #{checkpointAttestation.batchId}
                      {checkpointTotalUsd != null ? ` — total ${formatUsd(Number(checkpointTotalUsd))}` : ''}
                    </div>
                  ) : null}
                  <div>Token transfers: {tokenTransferCount.toLocaleString()}</div>
                  <div>Internal calls: {internalCallCount.toLocaleString()}</div>
                </div>
              </div>
              <div className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
                <div className="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Navigation</div>
                <div className="mt-3 flex flex-wrap gap-3 text-sm">
                  <Link href={`/blocks/${transaction.block_number}`} className="text-primary-600 hover:underline">
                    Open block
                  </Link>
                  <Link href={`/addresses/${transaction.from_address}`} className="text-primary-600 hover:underline">
                    Open sender
                  </Link>
                  {transaction.contract_address ? (
                    <Link href={`/addresses/${transaction.contract_address}`} className="text-primary-600 hover:underline">
                      Open created contract
                    </Link>
                  ) : null}
                </div>
              </div>
            </div>
          </Card>

          <SectionTabs tabs={tabs} activeTab={activeTab} onChange={setActiveTab} className="mb-6" />

          {activeTab === 'evidence' && complianceAssessment ? (
            <Card title="Transaction Evidence Matrix">
              <div className="space-y-4">
                <div className="flex flex-wrap items-center gap-3">
                  <EntityBadge label={`band ${complianceAssessment.grade}`} tone={complianceAssessment.score >= 80 ? 'success' : complianceAssessment.score >= 70 ? 'info' : 'warning'} />
                  <EntityBadge label={`score ${complianceAssessment.score}/100`} tone="info" />
                  <Link href="/docs/transaction-review" className="text-sm text-primary-600 hover:underline">
                    Scoring guide →
                  </Link>
                </div>
                <p className="text-sm text-gray-600 dark:text-gray-400">{complianceAssessment.summary}</p>
                <div className="grid gap-3 lg:grid-cols-2">
                  {complianceAssessment.factors.map((factor) => (
                    <div key={factor.label} className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
                      <div className="flex items-center justify-between gap-3">
                        <div className="text-sm font-medium text-gray-900 dark:text-white">{factor.label}</div>
                        <div className="text-sm text-gray-600 dark:text-gray-400">
                          {factor.score}/{factor.maxScore}
                        </div>
                      </div>
                      <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">{factor.summary}</div>
                    </div>
                  ))}
                </div>
              </div>
            </Card>
          ) : null}

          {activeTab === 'details' ? <Card title="Transaction Information">
            <dl className="space-y-4">
              <DetailRow label="Hash">
                <Address address={transaction.hash} />
              </DetailRow>
              <DetailRow label="Status">
                <span className={transaction.status === 1 ? 'text-green-600' : 'text-red-600'}>
                  {transaction.status === 1 ? 'Success' : 'Failed'}
                </span>
              </DetailRow>
              {transaction.method && (
                <DetailRow label="Method">
                  <code className="rounded bg-gray-100 px-2 py-1 text-xs dark:bg-gray-900">{transaction.method}</code>
                </DetailRow>
              )}
              <DetailRow label="Block">
                <Link href={`/blocks/${transaction.block_number}`} className="text-primary-600 hover:underline">
                  #{transaction.block_number}
                </Link>
              </DetailRow>
              <DetailRow label="Timestamp">{formatTimestamp(transaction.created_at)}</DetailRow>
              <DetailRow label="From">
                <Link href={`/addresses/${transaction.from_address}`} className="text-primary-600 hover:underline">
                  <Address address={transaction.from_address} truncate showCopy={false} />
                </Link>
              </DetailRow>
              {transaction.to_address && (
                <DetailRow label="To">
                  <Link href={`/addresses/${transaction.to_address}`} className="text-primary-600 hover:underline">
                    <Address address={transaction.to_address} truncate showCopy={false} />
                  </Link>
                </DetailRow>
              )}
              <DetailRow label="Value">
                {formatWeiAsEth(transaction.value)}
                {nativeValueUsd != null ? ` (${formatUsd(nativeValueUsd)})` : ''}
              </DetailRow>
              {transaction.fee && (
                <DetailRow label="Fee">
                  {formatWeiAsEth(transaction.fee)}
                  {nativeFeeUsd != null ? ` (${formatUsd(nativeFeeUsd)})` : ''}
                </DetailRow>
              )}
              <DetailRow label="Gas Price">
                {transaction.gas_price != null ? `${transaction.gas_price / 1e9} Gwei` : 'N/A'}
              </DetailRow>
              {transaction.gas_used != null && (
                <DetailRow label="Gas Used">
                  {transaction.gas_used.toLocaleString()} / {transaction.gas_limit.toLocaleString()}
                </DetailRow>
              )}
              {transaction.revert_reason && (
                <DetailRow label="Revert Reason">
                  <span className="text-red-600">{transaction.revert_reason}</span>
                </DetailRow>
              )}
              {transaction.contract_address && (
                <DetailRow label="Contract Created">
                  <Link href={`/addresses/${transaction.contract_address}`} className="text-primary-600 hover:underline">
                    <Address address={transaction.contract_address} truncate showCopy={false} />
                  </Link>
                </DetailRow>
              )}
            </dl>
          </Card> : null}

          {activeTab === 'details' && transaction.decoded_input && transaction.decoded_input.parameters.length > 0 && (
            <Card title="Decoded Input">
              <div className="space-y-4">
                <p className="text-sm text-gray-600 dark:text-gray-400">
                  {transaction.decoded_input.method_call || transaction.decoded_input.method_id || 'Decoded call'}
                </p>
                <dl className="space-y-3">
                  {transaction.decoded_input.parameters.map((parameter, index) => (
                    <DetailRow
                      key={`${parameter.name || parameter.type || 'parameter'}-${index}`}
                      label={parameter.name || `Param ${index + 1}`}
                    >
                      <div className="space-y-1">
                        {parameter.type && (
                          <div className="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">{parameter.type}</div>
                        )}
                        <pre className="overflow-x-auto whitespace-pre-wrap rounded-lg bg-gray-50 p-3 text-xs text-gray-800 dark:bg-gray-950 dark:text-gray-200">
                          {typeof parameter.value === 'string'
                            ? parameter.value
                            : JSON.stringify(parameter.value, null, 2)}
                        </pre>
                      </div>
                    </DetailRow>
                  ))}
                </dl>
              </div>
            </Card>
          )}

          {activeTab === 'transfers' ? <Card title="Token Transfers">
            <Table
              columns={tokenTransferColumns}
              data={pagedTokenTransfers}
              emptyMessage="No token transfers were indexed for this transaction."
              keyExtractor={(transfer) => `${transfer.token_address}-${transfer.from_address}-${transfer.to_address}-${transfer.amount}`}
            />
            <PaginationControls page={transferPage} pageCount={transferPageCount} onPageChange={setTransferPage} label="Token transfers" />
          </Card> : null}

          {activeTab === 'internal' ? <Card title="Internal Transactions">
            <Table
              columns={internalCallColumns}
              data={pagedInternalCalls}
              emptyMessage="No internal transactions were exposed for this transaction."
              keyExtractor={(call) => `${call.from_address}-${call.to_address || call.contract_address || 'unknown'}-${call.value}-${call.type || 'call'}`}
            />
            <PaginationControls page={internalPage} pageCount={internalPageCount} onPageChange={setInternalPage} label="Internal calls" />
          </Card> : null}

          {activeTab === 'raw' && transaction.input_data && (
            <Card title="Raw Input Data">
              <pre className="overflow-x-auto whitespace-pre-wrap break-all rounded-lg bg-gray-50 p-4 text-xs text-gray-800 dark:bg-gray-950 dark:text-gray-200">
                {transaction.input_data}
              </pre>
            </Card>
          )}
        </div>
      )}
    </div>
  )
}
