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

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

  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 {
    const globalTokens = this.registriesState.tokens.filter((t) => t.type === 'global');
    const ciTokens = this.registriesState.tokens.filter((t) => t.type === 'ci');

    return html`
      <ob-sectionheading>Tokens</ob-sectionheading>
      <sz-tokens-view
        .globalTokens=${globalTokens.map((t) => ({
          id: String(t.id),
          name: t.name,
          type: 'global' as const,
          createdAt: new Date(t.createdAt).toISOString(),
          lastUsed: t.lastUsedAt ? new Date(t.lastUsedAt).toISOString() : undefined,
        }))}
        .ciTokens=${ciTokens.map((t) => ({
          id: String(t.id),
          name: t.name,
          type: 'ci' as const,
          service: Array.isArray(t.scope) ? t.scope.join(', ') : undefined,
          createdAt: new Date(t.createdAt).toISOString(),
          lastUsed: t.lastUsedAt ? new Date(t.lastUsedAt).toISOString() : undefined,
        }))}
        @create=${(e: CustomEvent) => {
          appstate.dispatchProtectedAction(appstate.createRegistryTokenAction, {
            token: {
              name: `new-${e.detail.type}-token`,
              type: e.detail.type,
              scope: 'all',
              expiresIn: 'never',
            },
          });
        }}
        @delete=${(e: CustomEvent) => {
          appstate.dispatchProtectedAction(appstate.deleteRegistryTokenAction, {
            tokenId: Number(e.detail.id || e.detail.tokenId),
          });
        }}
      ></sz-tokens-view>
    `;
  }
}
