import gql from 'graphql-tag'
import { LitElement, html, css } from 'lit'
import { customElement, property } from 'lit/decorators.js'

import { client } from '@operato/graphql'

@customElement('credential-manager')
export class CredentialManager extends LitElement {
  @property({ type: Array }) credentials: {
    credentialId: string
  }[] = []

  static styles = css`
    div {
      margin: 20px;
    }
    button {
      margin: 5px;
    }
  `

  connectedCallback() {
    super.connectedCallback()
    this.fetchCredentials()
  }

  async fetchCredentials() {
    const response = await fetch('/auth/credentials', {
      method: 'GET',
      credentials: 'include'
    })
    this.credentials = await response.json()
  }

  async deleteCredential(credentialId: string) {
    const response = await fetch(`/credentials/${credentialId}`, {
      method: 'DELETE',
      credentials: 'include'
    })
    if (response.ok) {
      this.fetchCredentials()
    } else {
      console.error('Failed to delete credential')
    }
  }

  render() {
    return html`
      <div>
        <h2>Manage Your WebAuthn Credentials</h2>
        <ul>
          ${this.credentials.map(
            credential => html`
              <li>
                ${credential.credentialId}
                <button @click=${() => this.deleteCredential(credential.credentialId)}>Delete</button>
              </li>
            `
          )}
        </ul>
      </div>
    `
  }
}
