import '@components/General/Button';
import '@components/General/Select';
import { LitElement, css, html } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

@customElement('arx-setup-ccn-list')
export class CCNList extends LitElement {
  @property({ type: Array }) ccns: { name: string; pubkey: string }[] = [];

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

  @state() private selectedCCN: string | undefined;

  private _valueMapper = (ccn: { name: string; pubkey: string }) => ccn.pubkey;
  private _textMapper = (ccn: { name: string; pubkey: string }) => ccn.name;

  private _handleCCNSelected(pubkey: string | undefined) {
    this.selectedCCN = pubkey;
    this.dispatchEvent(new CustomEvent('ccn-selected', { detail: { ccn: this.selectedCCN } }));
  }

  override render() {
    if (this.ccns.length === 0)
      return html`
        <p>No CCNs found in the relay. You will be asked to setup a CCN in the next step.</p>
      `;

    if (this.ccns.length === 1)
      return html`
        <div>
          <h2>CCN Found</h2>
          <p>We found one CCN in your relay, which likely means you've used Eve before or there was an update introducing new setup steps. You can use this CCN to proceed with the setup, or create a new one.</p>
          <p>CCN Name: ${this.ccns[0].name}</p>
          <arx-button variant=${this.selectedCCN === this.ccns[0].pubkey ? 'accent' : 'secondary'} @click="${() => this._handleCCNSelected(this.ccns[0].pubkey)}" label="Use This CCN"></arx-button>
          <arx-button variant=${this.selectedCCN === undefined ? 'accent' : 'secondary'} @click="${() => this._handleCCNSelected(undefined)}" label="Create New CCN"></arx-button>
        </div>
      `;
    return html`
      <div>
        <h2>CCNs</h2>
        <p>We found the following CCNs in your relay, which likely means you've used Eve before or there was an update introducing new setup steps. You can quickly choose one of these CCNs to proceed with the setup, or create a new one.</p>
        <arx-select
          .options="${this.ccns}"
          .valueMapper="${this._valueMapper}"
          .textMapper="${this._textMapper}"
          @change="${(e: CustomEvent<{ value: string }>) => this._handleCCNSelected(e.detail.value)}"
        ></arx-select>
        <arx-button variant=${this.selectedCCN === undefined ? 'accent' : 'secondary'} @click="${() => this._handleCCNSelected(undefined)}" label="Create New CCN"></arx-button>
      </div>
    `;
  }
}
