import { wallet } from '@/wallet';
import type { ArxInputChangeEvent } from '@components/General/Input';
import { StateController } from '@lit-app/state';
import { LitElement, css, html } from 'lit';
import { customElement } from 'lit/decorators.js';

import '@components/General/Card';
import '@components/General/Input';
import '@components/WalletTransactionLine';

@customElement('arx-wallet-route')
export class WalletRoute extends LitElement {
  static override styles = css`
    h1 {
      text-align: center;
    }

    .transaction-list {
      background-color: var(--color-base-100);
      border-radius: var(--radius-card);
      padding: 20px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    .transaction-list h3 {
      color: var(--color-base-content);
      margin-bottom: 20px;
    }

    arx-wallet-transaction-line:last-child {
      border-bottom: none;
    }
  `;

  private inputToken = '';

  override async firstUpdated() {
    await wallet.loadWallet();
  }

  async doReceiveToken() {
    console.log('clicked', Date.now());
    await wallet.receiveToken(this.inputToken);
    this.inputToken = '';
  }

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

  override render() {
    return html`
      <arx-card>
        <h1>Wallet</h1>
        <hr />
        <h2>You have ${wallet.balance} sats</h2>
        <arx-input
          label="Token"
          .value=${this.inputToken}
          @change=${(e: ArxInputChangeEvent) => {
            if (!e.detail.value) return;
            this.inputToken = e.detail.value;
          }}
          type="text"
          id="token"
        ></arx-input>
        <arx-button label="Receive" @click=${this.doReceiveToken}></arx-button>
        <div class="transaction-list">
          <h3>Transaction History</h3>
          ${wallet.sortedHistory.map(
            (h) => html`<arx-wallet-transaction-line .transaction=${h}></arx-wallet-transaction-line>`,
          )}
        </div>
      </arx-card>
    `;
  }
}
