import { nanoid } from 'nanoid'
import '../../../src/md/button/ui-button.js'
import '../../../src/md/text-field/ui-filled-text-field.js'

function setupFormAction(): void {
  const u = new URL(window.location.href)
  const state = u.searchParams.get('state') as string
  const redirectUri = decodeURIComponent(u.searchParams.get('redirect_uri') as string)
  const type = u.searchParams.get('response_type')
  const codeParam = type === 'code' ? 'code' : 'access_token'
  const params = new URLSearchParams()
  params.set(codeParam, nanoid())
  params.set('state', state)
  params.set('expires_in', '3600')
  params.set('scope', 'dummy')
  if (type !== 'code') {
    params.set('token_type', 'bearer')
    params.set('refresh_token', nanoid())
  }
  const formUrl = `${redirectUri}#${params.toString()}`
  const form = document.querySelector('form') as HTMLFormElement
  form.action = formUrl
}

function loginHandler(): void {
  const form = document.querySelector('form') as HTMLFormElement
  window.location.assign(form.action)
}

function addButtonAction(): void {
  const button = document.querySelector('.login-button') as HTMLElement
  button.addEventListener('click', loginHandler)
}

function initialize(): void {
  setupFormAction()
  addButtonAction()
}

initialize()
