import { useLatestTransactions } from '../../hooks/useLatestTransactions';
import { explorerTxUrl, explorerAddressUrl, type ExplorerTx } from '../../services/explorer';
import { formatEther } from 'ethers';
import { Activity } from 'lucide-react';

const shortHash = (h: string) => `${h.slice(0, 10)}…${h.slice(-6)}`;
const shortAddr = (a: string) => `${a.slice(0, 6)}…${a.slice(-4)}`;
const formatMETA = (wei: string) => {
  try { return `${Number(formatEther(BigInt(wei))).toFixed(4)} META`; } catch { return `${wei} wei`; }
};
const relativeTime = (iso: string) => {
  const then = new Date(iso).getTime();
  const dt = Date.now() - then;
  if (dt < 60_000) return `${Math.max(1, Math.round(dt / 1000))}s ago`;
  if (dt < 3_600_000) return `${Math.round(dt / 60_000)}m ago`;
  return `${Math.round(dt / 3_600_000)}h ago`;
};

interface Props {
  /** Max rows to show (default 10). */
  limit?: number;
  /** Custom card header label — defaults to "Live Chain-138 Transactions". */
  title?: string;
}

/**
 * Renders the most recent on-chain transactions from SolaceScan.
 * Degraded state shows the error message; empty state shows a one-liner.
 * Links every hash/address to the explorer.
 */
export default function LiveTransactionsPanel({ limit = 10, title = 'Live Chain-138 Transactions' }: Props) {
  const { transactions, loading, error, lastUpdated } = useLatestTransactions(limit);

  return (
    <div className="dashboard-card live-transactions-card">
      <div className="card-header">
        <h3><Activity size={16} /> {title}</h3>
        <span className="small" style={{ color: '#6b7280' }}>
          {error
            ? <span style={{ color: '#ef4444' }}>RPC degraded · {error}</span>
            : loading
            ? 'loading…'
            : `${transactions.length} tx · ${lastUpdated ? lastUpdated.toLocaleTimeString() : '—'}`}
        </span>
      </div>
      <div className="live-transactions-list">
        {!loading && transactions.length === 0 && !error && (
          <div style={{ padding: 12, color: '#6b7280', fontSize: 12 }}>
            No transactions returned yet — SolaceScan may be indexing.
          </div>
        )}
        {transactions.map((tx: ExplorerTx) => (
          <div
            key={tx.hash}
            className="live-tx-row"
            style={{
              display: 'grid',
              gridTemplateColumns: '1.3fr 1fr 1fr 0.9fr 0.7fr 0.4fr',
              gap: 8,
              padding: '6px 12px',
              borderBottom: '1px solid rgba(255,255,255,0.04)',
              fontSize: 11,
              alignItems: 'center',
            }}
          >
            <a href={explorerTxUrl(tx.hash)} target="_blank" rel="noreferrer" className="mono" style={{ color: '#60a5fa' }}>
              {shortHash(tx.hash)}
            </a>
            <a href={explorerAddressUrl(tx.from.hash)} target="_blank" rel="noreferrer" className="mono" style={{ color: '#cbd5e1' }}>
              {shortAddr(tx.from.hash)}
            </a>
            <span className="mono" style={{ color: tx.to ? '#cbd5e1' : '#6b7280' }}>
              {tx.to ? shortAddr(tx.to.hash) : '— contract create —'}
            </span>
            <span className="mono">{formatMETA(tx.value)}</span>
            <span className="small" style={{ color: '#6b7280' }}>{relativeTime(tx.timestamp)}</span>
            <span style={{
              color: tx.status === 'error' ? '#ef4444' : tx.status === 'ok' ? '#22c55e' : '#eab308',
              fontSize: 9,
            }}>
              {tx.status ?? 'pending'}
            </span>
          </div>
        ))}
      </div>
      <div style={{ padding: '6px 12px', fontSize: 10, color: '#6b7280' }}>
        Source: <a href="https://explorer.d-bis.org" target="_blank" rel="noreferrer" style={{ color: '#60a5fa' }}>SolaceScan Explorer</a>
        {' · polls every 15s · Blockscout v2 /transactions'}
      </div>
    </div>
  );
}
