import * as plugins from '../plugins.js';
import * as shared from './shared/index.js';
import * as appstate from '../appstate.js';
import { appRouter } from '../router.js';
import {
  DeesElement,
  customElement,
  html,
  state,
  css,
  cssManager,
  type TemplateResult,
} from '@design.estate/dees-element';

@customElement('ob-view-registries')
export class ObViewRegistries extends DeesElement {
  @state()
  accessor registriesState: appstate.IRegistriesState = {
    tokens: [],
    registryStatus: null,
  };

  @state()
  accessor currentTab: 'onebox' | 'external' = 'onebox';

  constructor() {
    super();

    const registriesSub = appstate.registriesStatePart
      .select((s) => s)
      .subscribe((newState) => {
        this.registriesState = newState;
      });
    this.rxSubscriptions.push(registriesSub);
  }

  public static styles = [
    cssManager.defaultStyles,
    shared.viewHostCss,
    css``,
  ];

  async connectedCallback() {
    super.connectedCallback();
    await appstate.dispatchProtectedAction(
      appstate.fetchRegistryTokensAction,
      null,
    );
  }

  public render(): TemplateResult {
    switch (this.currentTab) {
      case 'external':
        return this.renderExternalView();
      default:
        return this.renderOneboxView();
    }
  }

  private renderOneboxView(): TemplateResult {
    return html`
      <ob-sectionheading>Registries</ob-sectionheading>
      <sz-registry-advertisement
        .status=${'running'}
        .registryUrl=${'localhost:5000'}
        @manage-tokens=${() => {
          // tokens are managed via the tokens view
          appRouter.navigateToView('tokens');
        }}
      ></sz-registry-advertisement>
    `;
  }

  private renderExternalView(): TemplateResult {
    return html`
      <ob-sectionheading>External Registries</ob-sectionheading>
      <sz-registry-external-view
        .registries=${[]}
        @add=${(e: CustomEvent) => {
          console.log('Add external registry:', e.detail);
        }}
      ></sz-registry-external-view>
    `;
  }
}
