import { html, TemplateResult } from 'lit'
import { IOidcAuthorization } from '@api-client/core/models/Authorization.js'
import { type IRequestAuthorization, RequestAuthorization } from '@api-client/core/models/RequestAuthorization.js'
import reactive from '../../../src/decorators/reactive.js'
import { DemoPage } from '../../../src/demo/DemoPage.js'
import { Authorization } from '../../../src/elements/authorization/ui/Authorization.js'
import '../../../src/define/authorization/oidc-authorization.js'
import '../../../src/define/authorization/oidc-authorize.js'
import env from './env.js'

const STORE_KEY = 'authorization.openId.configuration'

class ComponentDemo extends DemoPage {
  override accessor componentName = 'OpenID Connect authorization'

  @reactive() accessor authorization: IRequestAuthorization

  @reactive() accessor issuers: string[]

  constructor() {
    super()

    this.restoreAuth()
    this.authorization = this.defaultAuthorization()

    // this.issuerUri = env.oauth2.issuer;
    this.issuers = [
      env.oauth2.issuer,
      'https://accounts.google.com/',
      'https://login.salesforce.com/',
      'https://phantauth.net/',
      'https://www.paypalobjects.com/',
      'https://api.login.yahoo.com/',
      'https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/v2.0/',
    ]
  }

  restoreAuth(): void {
    const data = localStorage.getItem(STORE_KEY)
    if (!data) {
      return
    }
    try {
      const tmp = JSON.parse(data)
      if (tmp) {
        this.authorization = tmp
      }
    } catch {
      //
    }
  }

  defaultAuthorization(): IRequestAuthorization {
    // these cid and cs are only allowed for localhost testing.
    // Other origins are banned.
    const cid = '1076318174169-5i48tqquddrk0lv0shbtsaj6kc8c9j5g.apps.googleusercontent.com'
    const cs = 'SF3kI7tqI_BUdc5ACkJ4vjII'
    const auth = RequestAuthorization.fromTypedConfig(
      'open id',
      {
        redirectUri: new URL('/demo/elements/authorization/oauth-popup.html', window.location.href).toString(),
        credentialsSource: [
          {
            grantType: 'client_credentials',
            credentials: [
              { name: 'My social Network', clientId: '123', clientSecret: 'xyz' },
              { name: 'My social Network 2', clientId: '1234', clientSecret: 'wxyz' },
            ],
          },
        ],
        clientId: cid,
        clientSecret: cs,
        issuerUri: 'https://accounts.google.com/',
      } as IOidcAuthorization,
      false
    )
    return auth.toJSON()
  }

  handleIssuerChange(e: Event): void {
    const input = e.target as HTMLSelectElement
    const auth = RequestAuthorization.fromTypedConfig(
      'open id',
      {
        issuerUri: input.value,
        redirectUri: new URL('/demo/elements/authorization/oauth-popup.html', window.location.href).toString(),
      } as IOidcAuthorization,
      false
    )
    this.authorization = auth.toJSON()
  }

  handleChange(e: Event): void {
    const input = e.target as Authorization
    if (input.authorization) {
      this.authorization = input.authorization
      localStorage.setItem(STORE_KEY, JSON.stringify(this.authorization))
    }
    console.log('Value changed', this.authorization)
  }

  handleDelete(): void {
    console.log('Requested to delete.')
  }

  contentTemplate(): TemplateResult {
    const auth = this.authorization as IRequestAuthorization
    const config = auth.config as IOidcAuthorization
    return html`
      <a href="./">Back</a>
      <section class="demo-section">
        <oidc-authorization
          .authorization="${this.authorization as IRequestAuthorization}"
          @change="${this.handleChange}"
          @delete="${this.handleDelete}"
        ></oidc-authorization>
      </section>

      <div>
        <label for="issuer-uri">Issuer URI:</label>
        <select
          id="issuer-uri"
          name="issuer-uri"
          @change="${this.handleIssuerChange}"
          @blur="${this.handleIssuerChange}"
        >
          ${this.issuers.map(
            (uri) => html`<option ?selected="${uri === config.issuerUri}" value="${uri}">${uri}</option>`
          )}
        </select>
      </div>

      <oidc-authorize tokenProxy="${env.oauth2.tokenProxy}"></oidc-authorize>
    `
  }
}

const instance = new ComponentDemo()
instance.render()
