import * as plugins from '../plugins.js';
import * as appstate from '../appstate.js';
import * as shared from './shared/index.js';

import {
  DeesElement,
  customElement,
  html,
  state,
  css,
  cssManager,
  type TemplateResult,
} from '@design.estate/dees-element';
import { DeesModal } from '@design.estate/dees-catalog';

@customElement('objst-view-credentials')
export class ObjstViewCredentials extends DeesElement {
  @state()
  accessor credentialsState: appstate.ICredentialsState = { credentials: [] };

  constructor() {
    super();
    const sub = appstate.credentialsStatePart
      .select((s) => s)
      .subscribe((credentialsState) => {
        this.credentialsState = credentialsState;
      });
    this.rxSubscriptions.push(sub);
  }

  async connectedCallback() {
    super.connectedCallback();
    appstate.credentialsStatePart.dispatchAction(appstate.fetchCredentialsAction, null);
  }

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

  public render(): TemplateResult {
    return html`
      <objst-sectionheading>Access Keys</objst-sectionheading>
      <dees-table
        heading1="Access Credentials"
        heading2="Manage access keys for API authentication"
        .data=${this.credentialsState.credentials}
        .dataName=${'credential'}
        .displayFunction=${(item: any) => ({
          'Access Key ID': item.accessKeyId,
          'Secret Access Key': item.secretAccessKey,
        })}
        .dataActions=${[
          {
            name: 'Add Key',
            iconName: 'lucide:plus',
            type: ['header'] as any[],
            actionFunc: async () => {
              await this.showAddKeyModal();
            },
          },
          {
            name: 'Remove',
            iconName: 'lucide:trash2',
            type: ['inRow', 'contextmenu'] as any[],
            actionFunc: async (args: any) => {
              await this.showRemoveKeyModal(args.item.accessKeyId);
            },
          },
        ]}
      ></dees-table>
    `;
  }

  private async showAddKeyModal(): Promise<void> {
    await DeesModal.createAndShow({
      heading: 'Add Access Key',
      content: html`
        <dees-form>
          <dees-input-text .key=${'accessKeyId'} .label=${'Access Key ID'} .required=${true}></dees-input-text>
          <dees-input-text .key=${'secretAccessKey'} .label=${'Secret Access Key'} .required=${true}></dees-input-text>
        </dees-form>
      `,
      menuOptions: [
        {
          name: 'Cancel',
          action: async (modal: any) => { modal.destroy(); },
        },
        {
          name: 'Add',
          action: async (modal: any) => {
            const form = modal.shadowRoot.querySelector('dees-form') as any;
            const data = await form.collectFormData();
            if (data.accessKeyId && data.secretAccessKey) {
              await appstate.credentialsStatePart.dispatchAction(appstate.addCredentialAction, {
                accessKeyId: data.accessKeyId,
                secretAccessKey: data.secretAccessKey,
              });
            }
            modal.destroy();
          },
        },
      ],
    });
  }

  private async showRemoveKeyModal(accessKeyId: string): Promise<void> {
    await DeesModal.createAndShow({
      heading: 'Remove Access Key',
      content: html`<p>Are you sure you want to remove access key <strong>${accessKeyId}</strong>?</p>`,
      menuOptions: [
        {
          name: 'Cancel',
          action: async (modal: any) => { modal.destroy(); },
        },
        {
          name: 'Remove',
          action: async (modal: any) => {
            await appstate.credentialsStatePart.dispatchAction(appstate.removeCredentialAction, {
              accessKeyId,
            });
            modal.destroy();
          },
        },
      ],
    });
  }
}
