import satsComma from '@/utils/satsComma';
import { wallet } from '@/wallet';
import '@components/General/Fieldset';
import '@components/LoadingView';
import '@components/WalletTransactionLine';
import { StateController } from '@lit-app/state';
import { LitElement, css, html } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import { when } from 'lit/directives/when.js';

@customElement('arx-wallet-widget')
export class WalletWidget extends LitElement {
  @state()
  public loading = false;

  override connectedCallback(): void {
    super.connectedCallback();
    new StateController(this, wallet);
  }

  override async firstUpdated() {
    this.loading = true;
    await wallet.loadWallet();
    this.loading = false;
  }

  static override styles = [
    css`
      :host {
        display: block;
      }

      .widget-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
        border-bottom: var(--border) solid var(--color-base-300);
        padding-bottom: 8px;
      }

      .widget-title {
        font-size: 1.2rem;
        font-weight: 600;
        margin: 0;
        color: var(--color-base-content);
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .bitcoin-icon {
        color: var(--color-warning);
        font-size: 1.4rem;
      }
    `,
  ];

  override render() {
    return html`
      <div class="widget-header">
        <h3 class="widget-title">
          <span class="bitcoin-icon">₿</span> Bitcoin Wallet
        </h3>
      </div>
      <arx-fieldset .legend=${when(
        this.loading,
        () => 'Loading...',
        () => `${satsComma(wallet.balance)} sats`,
      )}>
        ${when(
          wallet.sortedHistory.length > 0,
          () => html`
            Latest Transaction:
            <arx-wallet-transaction-line .transaction=${wallet.sortedHistory[0]}></arx-wallet-transaction-line>
          `,
          () => 'No transactions yet',
        )}
      </arx-fieldset>
    `;
  }
}
