// WalletDetailPane — right pane of the Wallet section. Either the
// selected tx's detail or a placeholder when nothing is selected.

import React, { useEffect, useState } from 'react';
import { useStore } from '@/lib/store';
import { getTxDetail, type TxDetail } from '@/lib/api';
import { shortAddr } from '@/lib/crypto';

function formatT(ut: number | string): string {
  const n = typeof ut === 'string' ? parseInt(ut, 10) : ut;
  if (!Number.isFinite(n)) return '—';
  return (n / 1_000_000).toLocaleString(undefined, { maximumFractionDigits: 6 });
}

export function WalletDetailPane(): React.ReactElement {
  const sel = useStore(s => s.walletSel);
  const keyFile = useStore(s => s.keyFile);
  const [tx, setTx]   = useState<TxDetail | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (sel.kind !== 'tx') { setTx(null); return; }
    let cancelled = false;
    setLoading(true);
    getTxDetail(sel.id)
      .then(t => { if (!cancelled) setTx(t); })
      .catch(() => { if (!cancelled) setTx(null); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [sel]);

  if (sel.kind !== 'tx') {
    return (
      <div style={{
        height: '100%', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        color: '#6a6a6a', fontSize: 13, padding: 40, textAlign: 'center',
      }}>
        Pick a transaction from the list on the left to see its details.
      </div>
    );
  }

  if (loading) return <Placeholder note="Loading…" />;
  if (!tx)     return <Placeholder note="Transaction not found on this node." />;

  const outgoing = !!keyFile && tx.from === keyFile.pub_key;
  const amountUT = tx.amount_ut;
  const amountColor = amountUT === 0 ? '#8b8b8b'
    : outgoing ? '#f0b35a' : '#3ba55d';

  return (
    <div style={{
      height: '100%', overflowY: 'auto',
      padding: '20px 24px', background: '#000',
    }}>
      <div style={{ color: '#8b8b8b', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase' }}>
        {tx.type.replace(/_/g, ' ')}
      </div>
      <div style={{
        color: amountColor, fontSize: 30, fontWeight: 800, marginTop: 4,
      }}>
        {amountUT === 0 ? '—' : `${outgoing ? '−' : '+'}${formatT(amountUT)} T`}
      </div>
      {tx.memo && (
        <div style={{ color: '#e0e0e0', fontSize: 13, marginTop: 6, fontStyle: 'italic' }}>
          “{tx.memo}”
        </div>
      )}

      <div style={{
        marginTop: 22, display: 'grid',
        gridTemplateColumns: 'minmax(120px, auto) 1fr', rowGap: 10, columnGap: 20,
      }}>
        <Cell label="ID">{tx.id}</Cell>
        <Cell label="From">{tx.from_addr ?? shortAddr(tx.from, 8)}</Cell>
        {tx.to && <Cell label="To">{tx.to_addr ?? shortAddr(tx.to, 8)}</Cell>}
        <Cell label="Amount">{formatT(tx.amount_ut)} T</Cell>
        <Cell label="Fee">{formatT(tx.fee_ut)} T</Cell>
        <Cell label="Time">{new Date(tx.time).toLocaleString()}</Cell>
        <Cell label="Block">#{tx.block_index} · {shortAddr(tx.block_hash, 8)}</Cell>
        {typeof tx.gas_used === 'number' && tx.gas_used > 0 && (
          <Cell label="Gas used">{tx.gas_used.toLocaleString()}</Cell>
        )}
      </div>

      {Boolean(tx.payload) && (
        <details style={{
          marginTop: 22, background: '#0a0a0a',
          borderRadius: 10, border: '1px solid #1f1f1f', padding: 12,
        }}>
          <summary style={{ cursor: 'pointer', color: '#8b8b8b', fontSize: 12, fontWeight: 700 }}>
            Payload
          </summary>
          <pre className="selectable" style={{
            marginTop: 8, color: '#d0d0d0', fontSize: 11, lineHeight: 1.5,
            whiteSpace: 'pre-wrap', wordBreak: 'break-word',
          }}>
{JSON.stringify(tx.payload, null, 2)}
          </pre>
        </details>
      )}

      {tx.payload_hex && (
        <details style={{
          marginTop: 10, background: '#0a0a0a',
          borderRadius: 10, border: '1px solid #1f1f1f', padding: 12,
        }}>
          <summary style={{ cursor: 'pointer', color: '#8b8b8b', fontSize: 12, fontWeight: 700 }}>
            Payload (hex)
          </summary>
          <div className="selectable" style={{
            marginTop: 8, color: '#d0d0d0', fontSize: 11, fontFamily: 'monospace',
            wordBreak: 'break-all',
          }}>
            {tx.payload_hex}
          </div>
        </details>
      )}
    </div>
  );
}

function Cell({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <>
      <div style={{
        color: '#8b8b8b', fontSize: 11, fontWeight: 700,
        letterSpacing: 1, textTransform: 'uppercase',
      }}>{label}</div>
      <div className="selectable" style={{
        color: '#fff', fontSize: 13, fontFamily: 'monospace',
        wordBreak: 'break-all',
      }}>{children}</div>
    </>
  );
}

function Placeholder({ note }: { note: string }) {
  return (
    <div style={{
      height: '100%', display: 'flex',
      alignItems: 'center', justifyContent: 'center',
      color: '#6a6a6a', fontSize: 13, padding: 40,
    }}>{note}</div>
  );
}
