import type { GetServerSideProps } from 'next'
import AnalyticsOperationsPage from '@/components/explorer/AnalyticsOperationsPage'
import { normalizeBlock, normalizeTransaction } from '@/services/api/blockscout'
import {
  normalizeTransactionTrend,
  summarizeRecentTransactions,
  type ExplorerRecentActivitySnapshot,
  type ExplorerStats,
  type ExplorerTransactionTrendPoint,
} from '@/services/api/stats'
import type { Block } from '@/services/api/blocks'
import type { Transaction } from '@/services/api/transactions'
import type { MissionControlBridgeStatusResponse } from '@/services/api/missionControl'
import { fetchPublicJson } from '@/utils/publicExplorer'
import { fetchExplorerTruthContext } from '@/utils/serverExplorerContext'

interface AnalyticsPageProps {
  initialStats: ExplorerStats | null
  initialTransactionTrend: ExplorerTransactionTrendPoint[]
  initialActivitySnapshot: ExplorerRecentActivitySnapshot | null
  initialBlocks: Block[]
  initialTransactions: Transaction[]
  initialBridgeStatus: MissionControlBridgeStatusResponse | null
}

function serializeBlocks(blocks: Block[]): Block[] {
  return JSON.parse(
    JSON.stringify(
      blocks.map((block) => ({
        chain_id: block.chain_id,
        number: block.number,
        hash: block.hash,
        timestamp: block.timestamp,
        miner: block.miner,
        gas_used: block.gas_used,
        gas_limit: block.gas_limit,
        transaction_count: block.transaction_count,
      })),
    ),
  ) as Block[]
}

function serializeTransactions(transactions: Transaction[]): Transaction[] {
  return JSON.parse(
    JSON.stringify(
      transactions.map((transaction) => ({
        hash: transaction.hash,
        block_number: transaction.block_number,
        from_address: transaction.from_address,
        to_address: transaction.to_address ?? null,
        value: transaction.value,
        status: transaction.status ?? null,
        contract_address: transaction.contract_address ?? null,
        fee: transaction.fee ?? null,
      })),
    ),
  ) as Transaction[]
}

export default function AnalyticsPage(props: AnalyticsPageProps) {
  return <AnalyticsOperationsPage {...props} />
}

export const getServerSideProps: GetServerSideProps<AnalyticsPageProps> = async () => {
  const chainId = Number(process.env.NEXT_PUBLIC_CHAIN_ID || '138')
  const [truthContextResult, trendResult, activityResult, blocksResult, transactionsResult] = await Promise.allSettled([
    fetchExplorerTruthContext(),
    fetchPublicJson('/api/v2/stats/charts/transactions'),
    fetchPublicJson('/api/v2/main-page/transactions'),
    fetchPublicJson('/api/v2/blocks?page=1&page_size=5'),
    fetchPublicJson('/api/v2/transactions?page=1&page_size=5'),
  ])

  return {
    props: {
      initialStats: truthContextResult.status === 'fulfilled' ? truthContextResult.value.initialStats : null,
      initialTransactionTrend:
        trendResult.status === 'fulfilled' ? normalizeTransactionTrend(trendResult.value as never) : [],
      initialActivitySnapshot:
        activityResult.status === 'fulfilled' ? summarizeRecentTransactions(activityResult.value as never) : null,
      initialBlocks:
        blocksResult.status === 'fulfilled' && Array.isArray((blocksResult.value as { items?: unknown[] })?.items)
          ? serializeBlocks(
              ((blocksResult.value as { items?: unknown[] }).items || []).map((item) =>
                normalizeBlock(item as never, chainId),
              ),
            )
          : [],
      initialTransactions:
        transactionsResult.status === 'fulfilled' && Array.isArray((transactionsResult.value as { items?: unknown[] })?.items)
          ? serializeTransactions(
              ((transactionsResult.value as { items?: unknown[] }).items || []).map((item) =>
                normalizeTransaction(item as never, chainId),
              ),
            )
          : [],
      initialBridgeStatus:
        truthContextResult.status === 'fulfilled' ? truthContextResult.value.initialBridgeStatus : null,
    },
  }
}
