'use client'

import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import { Card, Table, Address } from '@/libs/frontend-ui-primitives'
import Link from 'next/link'
import { addressesApi, AddressInfo, TransactionSummary } from '@/services/api/addresses'

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

  const [addressInfo, setAddressInfo] = useState<AddressInfo | null>(null)
  const [transactions, setTransactions] = useState<TransactionSummary[]>([])
  const [loading, setLoading] = useState(true)

  const loadAddressInfo = useCallback(async () => {
    try {
      const { ok, data } = await addressesApi.getSafe(chainId, address)
      if (!ok) {
        setAddressInfo(null)
        return
      }
      setAddressInfo(data ?? null)
    } catch (error) {
      console.error('Failed to load address info:', error)
      setAddressInfo(null)
    }
  }, [chainId, address])

  const loadTransactions = useCallback(async () => {
    try {
      const { ok, data } = await addressesApi.getTransactionsSafe(chainId, address, 1, 20)
      setTransactions(ok ? data : [])
    } catch (error) {
      console.error('Failed to load transactions:', error)
      setTransactions([])
    } finally {
      setLoading(false)
    }
  }, [chainId, address])

  useEffect(() => {
    if (!router.isReady || !address) {
      setLoading(router.isReady ? false : true)
      if (router.isReady && !address) {
        setAddressInfo(null)
        setTransactions([])
      }
      return
    }
    loadAddressInfo()
    loadTransactions()
  }, [address, loadAddressInfo, loadTransactions, router.isReady])

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

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

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

  const transactionColumns = [
    {
      header: 'Hash',
      accessor: (tx: TransactionSummary) => (
        <Link href={`/transactions/${tx.hash}`} className="text-primary-600 hover:underline">
          <Address address={tx.hash} truncate />
        </Link>
      ),
    },
    {
      header: 'Block',
      accessor: (tx: TransactionSummary) => (
        <Link href={`/blocks/${tx.block_number}`} className="text-primary-600 hover:underline">
          {tx.block_number}
        </Link>
      ),
    },
    {
      header: 'To',
      accessor: (tx: TransactionSummary) => tx.to_address ? (
        <Link href={`/addresses/${tx.to_address}`} className="text-primary-600 hover:underline">
          <Address address={tx.to_address} truncate />
        </Link>
      ) : 'Contract Creation',
    },
    {
      header: 'Value',
      accessor: (tx: TransactionSummary) => {
        const value = BigInt(tx.value)
        const eth = Number(value) / 1e18
        return eth > 0 ? `${eth.toFixed(4)} ETH` : '0 ETH'
      },
    },
    {
      header: 'Status',
      accessor: (tx: TransactionSummary) => (
        <span className={tx.status === 1 ? 'text-green-600' : 'text-red-600'}>
          {tx.status === 1 ? 'Success' : 'Failed'}
        </span>
      ),
    },
  ]

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">
        {addressInfo.label || 'Address'}
      </h1>

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

      <Card title="Address Information" className="mb-6">
        <div className="space-y-4">
          <div>
            <span className="font-semibold">Address:</span>
            <Address address={addressInfo.address} className="ml-2" />
          </div>
          {addressInfo.tags.length > 0 && (
            <div>
              <span className="font-semibold">Tags:</span>
              <div className="flex gap-2 mt-1">
                {addressInfo.tags.map((tag, i) => (
                  <span key={i} className="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded text-sm">
                    {tag}
                  </span>
                ))}
              </div>
            </div>
          )}
          <div>
            <span className="font-semibold">Transactions:</span>
            <span className="ml-2">{addressInfo.transaction_count}</span>
          </div>
          <div>
            <span className="font-semibold">Tokens:</span>
            <span className="ml-2">{addressInfo.token_count}</span>
          </div>
          <div>
            <span className="font-semibold">Type:</span>
            <span className="ml-2">{addressInfo.is_contract ? 'Contract' : 'EOA'}</span>
          </div>
        </div>
      </Card>

      <Card title="Transactions">
        <Table columns={transactionColumns} data={transactions} keyExtractor={(tx) => tx.hash} />
      </Card>
    </div>
  )
}
