'use client'

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

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

  const [transaction, setTransaction] = useState<Transaction | null>(null)
  const [loading, setLoading] = useState(true)

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

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

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

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

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

  const value = BigInt(transaction.value)
  const ethValue = Number(value) / 1e18

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

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

      <Card title="Transaction Information">
        <div className="space-y-4">
          <div>
            <span className="font-semibold">Hash:</span>
            <Address address={transaction.hash} className="ml-2" />
          </div>
          <div>
            <span className="font-semibold">Block:</span>
            <Link href={`/blocks/${transaction.block_number}`} className="ml-2 text-primary-600 hover:underline">
              #{transaction.block_number}
            </Link>
          </div>
          <div>
            <span className="font-semibold">From:</span>
            <Link href={`/addresses/${transaction.from_address}`} className="ml-2">
              <Address address={transaction.from_address} truncate />
            </Link>
          </div>
          {transaction.to_address && (
            <div>
              <span className="font-semibold">To:</span>
              <Link href={`/addresses/${transaction.to_address}`} className="ml-2">
                <Address address={transaction.to_address} truncate />
              </Link>
            </div>
          )}
          <div>
            <span className="font-semibold">Value:</span>
            <span className="ml-2">{ethValue.toFixed(4)} ETH</span>
          </div>
          {transaction.gas_price && (
            <div>
              <span className="font-semibold">Gas Price:</span>
              <span className="ml-2">{transaction.gas_price / 1e9} Gwei</span>
            </div>
          )}
          {transaction.gas_used && (
            <div>
              <span className="font-semibold">Gas Used:</span>
              <span className="ml-2">{transaction.gas_used.toLocaleString()} / {transaction.gas_limit.toLocaleString()}</span>
            </div>
          )}
          <div>
            <span className="font-semibold">Status:</span>
            <span className={`ml-2 ${transaction.status === 1 ? 'text-green-600' : 'text-red-600'}`}>
              {transaction.status === 1 ? 'Success' : 'Failed'}
            </span>
          </div>
          {transaction.contract_address && (
            <div>
              <span className="font-semibold">Contract Created:</span>
              <Link href={`/addresses/${transaction.contract_address}`} className="ml-2">
                <Address address={transaction.contract_address} truncate />
              </Link>
            </div>
          )}
        </div>
      </Card>
    </div>
  )
}
