import { TxInfo } from '../api';

interface OverviewTabProps {
  balance: { balance_btc: number; balance_sats: number } | null;
  btcPrice: number;
  utxos: any[];
  txHistory: TxInfo[];
  blockCount: number | null;
  feeEstimate: any;
  networkInfo: any;
  wallet: any;
  addresses: string[];
}

function fmtBtc(sats: number) {
  return (sats / 100_000_000).toFixed(8);
}

function fmtDate(ts: number | null) {
  if (!ts) return '—';
  const d = new Date(ts * 1000);
  if (isNaN(d.getTime())) return '—';
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

export default function OverviewTab({
  balance,
  btcPrice,
  utxos,
  txHistory,
  blockCount,
  feeEstimate,
  networkInfo,
  wallet,
  addresses,
}: OverviewTabProps) {
  const totalUtxoValue = utxos.reduce((sum, u) => sum + (u.amount || 0), 0);
  const recentTxs = txHistory.slice(0, 5);

  return (
    <div className="tab-content">
      {/* Stats Grid */}
      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Balance</div>
          <div className="stat-value">
            {balance ? fmtBtc(balance.balance_sats) : '—'}
            <span className="text-tertiary" style={{ fontSize: '14px', marginLeft: '6px' }}>BTC</span>
          </div>
          {btcPrice > 0 && balance && (
            <div className="stat-sub">
              ≈ ${(balance.balance_sats / 100_000_000 * btcPrice).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            </div>
          )}
        </div>

        <div className="stat-card">
          <div className="stat-label">UTXOs</div>
          <div className="stat-value">{utxos.length}</div>
          <div className="stat-sub">{fmtBtc(totalUtxoValue)} BTC total</div>
        </div>

        <div className="stat-card">
          <div className="stat-label">Block Height</div>
          <div className="stat-value mono">{blockCount ?? '—'}</div>
        </div>

        <div className="stat-card">
          <div className="stat-label">Fee Rate</div>
          <div className="stat-value mono">
            {feeEstimate ? `${feeEstimate.feerate_sats_vb}` : '—'}
            <span className="text-tertiary" style={{ fontSize: '14px', marginLeft: '6px' }}>sats/vB</span>
          </div>
          {feeEstimate && (
            <div className="stat-sub">
              ~{feeEstimate.estimated_fee_btc.toFixed(8)} BTC fee
            </div>
          )}
        </div>
      </div>

      {/* Wallet Info */}
      {wallet && (
        <div className="section">
          <div className="section-header">
            <h3>Wallet</h3>
          </div>
          <div className="info-grid">
            <div className="info-row">
              <span className="info-label">Name</span>
              <span className="mono">{wallet.name}</span>
            </div>
            <div className="info-row">
              <span className="info-label">Fingerprint</span>
              <span className="mono">{wallet.fingerprint}</span>
            </div>
            <div className="info-row">
              <span className="info-label">Addresses</span>
              <span className="mono">{addresses.length}</span>
            </div>
            {wallet.ext_pub_key && (
              <div className="info-row">
                <span className="info-label">Descriptor</span>
                <span className="mono" style={{ fontSize: '11px', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {wallet.ext_pub_key.slice(0, 40)}…
                </span>
              </div>
            )}
            <div className="info-row">
              <span className="info-label">Type</span>
              <span>{wallet.wallet_type}</span>
            </div>
          </div>
        </div>
      )}

      {/* Network Status */}
      {networkInfo && (
        <div className="section">
          <div className="section-header">
            <h3>Network</h3>
          </div>
          <div className="info-grid">
            <div className="info-row">
              <span className="info-label">Node</span>
              <span>{networkInfo.node_type}</span>
            </div>
            <div className="info-row">
              <span className="info-label">Network</span>
              <span>{networkInfo.network}</span>
            </div>
            {networkInfo.peers !== undefined && (
              <div className="info-row">
                <span className="info-label">Peers</span>
                <span>{networkInfo.peers}</span>
              </div>
            )}
            {networkInfo.version && (
              <div className="info-row">
                <span className="info-label">Version</span>
                <span>{networkInfo.version}</span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Recent Transactions */}
      <div className="section">
        <div className="section-header">
          <h3>Recent Transactions</h3>
          {recentTxs.length === 0 && (
            <span className="text-tertiary" style={{ fontSize: '13px' }}>No transactions yet</span>
          )}
        </div>
        {recentTxs.length > 0 && (
          <table className="wallet-table">
            <thead>
              <tr>
                <th>TXID</th>
                <th>Date</th>
                <th>Amount</th>
                <th>Confirmations</th>
              </tr>
            </thead>
            <tbody>
              {recentTxs.map(tx => (
                <tr key={tx.txid}>
                  <td className="mono" style={{ fontSize: '12px' }}>
                    {tx.txid.slice(0, 10)}…{tx.txid.slice(-4)}
                  </td>
                  <td>{fmtDate(tx.time || null)}</td>
                  <td className={`mono ${tx.amount < 0 ? 'text-red' : 'text-green'}`}>
                    {tx.amount < 0
                      ? `${tx.amount.toFixed(8)}`
                      : `+${tx.amount.toFixed(8)}`
                    }
                  </td>
                  <td>
                    <span className={`badge ${tx.confirmations > 0 ? 'badge-green' : 'badge-yellow'}`}>
                      {tx.confirmations > 0 ? `${tx.confirmations} conf` : 'unconfirmed'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}