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

const STORE_KEY = 'demo.authorization.editor.oauth2'

class ComponentDemoPage extends DemoPage {
  override accessor componentName = 'OAuth 2 authorization'

  @reactive() accessor authorization: IRequestAuthorization

  constructor() {
    super()
    const auth = this.restoreAuth()
    if (auth) {
      this.authorization = auth
    } else {
      this.authorization = this.defaultAuthorization()
    }
  }

  restoreAuth(): IRequestAuthorization | undefined {
    const data = localStorage.getItem(STORE_KEY)
    if (!data) {
      return
    }
    try {
      const tmp = JSON.parse(data)
      if (tmp) {
        return tmp
      }
    } catch {
      //
    }
  }

  defaultAuthorization(): IRequestAuthorization {
    const auth = RequestAuthorization.fromTypedConfig(
      'oauth 2',
      {
        grantType: 'authorization_code',
        scopes: ['profile', 'email'],
        authorizationUri: new URL('/demo/elements/authorization/oauth-authorize.html', window.location.href).toString(),
        redirectUri: new URL('/demo/elements/authorization/oauth-popup.html', window.location.href).toString(),
        accessTokenUri: `${window.location.origin}/auth/token`,
        credentialsSource: [
          {
            grantType: 'client_credentials',
            credentials: [
              { name: 'My social Network', clientId: '123', clientSecret: 'xyz' },
              { name: 'My social Network 2', clientId: '1234', clientSecret: 'wxyz' },
            ],
          },
        ],
        clientId: 'test-client-id',
        clientSecret: 'test-client-secret',
        pkce: true,
      } as IOAuth2Authorization,
      false
    )
    return 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 {
    return html`
      <a href="./">Back</a>
      <section class="demo-section">
        <oauth2-authorization
          .authorization="${this.authorization as IRequestAuthorization}"
          @change="${this.handleChange}"
          @delete="${this.handleDelete}"
        ></oauth2-authorization>
      </section>

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

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