<template>
  <div class="min-h-screen bg-gray-100 flex items-center justify-center p-4">
    <div class="max-w-md w-full bg-white rounded-xl shadow-lg p-8">
      <h2 class="text-2xl font-bold text-gray-900 mb-6 text-center">Sign In</h2>

      <form @submit.prevent="submitLogin" class="space-y-4">
        <div>
          <sl-input
            label="Username"
            class="w-full"
            placeholder="Username"
            autocomplete="username"
            required=""
            :value="username"
            @input="username = $event.target.value"
          ></sl-input>
        </div>
        <div>
          <sl-input
            label="Password"
            type="password"
            class="w-full"
            :value="password"
            @input="password = $event.target.value"
            placeholder="••••••••"
            autocomplete="current-password"
            required=""
          ></sl-input>
        </div>
        <sl-button type="submit" variant="primary" class="w-full"> Login </sl-button>
      </form>
      <template v-if="oidcProvider">
        <div class="w-full items-center text-center my-4 flex">
          <div class="w-full h-[0.125rem] box-border bg-gray-200 dark:bg-gray-700"></div>
          <div class="px-4 text-lg text-sm font-medium text-gray-500 dark:text-gray-400">Or</div>
          <div class="w-full h-[0.125rem] box-border bg-gray-200 dark:bg-gray-700"></div>
        </div>
        <div class="w-full text-center my-4">
          <sl-button outline variant="neutral" :href="oidcLoginUrl">
            Sign in with {{ oidcProvider }}
          </sl-button>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useAuthTokenStore } from '@/store/auth'
import { useRouter } from 'vue-router'
import { useAlertsStore } from '@/store/useAlertsStore'
import '@shoelace-style/shoelace/dist/components/alert/alert.js'

const username = ref('')
const password = ref('')

const auth = useAuthTokenStore()
const router = useRouter()

const alerts = useAlertsStore()

const oidcProvider = ref<string | null>()

async function checkOidcProvider() {
  const provider = await auth.getOidcProvider()
  console.log(provider)
  if (provider) {
    console.log('OIDC Provider: ', provider)
    oidcProvider.value = provider
  }
}

const baseURL = import.meta.env.SSHECRET_FRONTEND_API_BASE_URL
const oidcLoginUrl = baseURL + '/api/v1/oidc/login'

async function submitLogin() {
  error.value = false
  const success = await auth.login(username.value, password.value)
  if (success) {
    router.push('/')
  } else {
    alerts.showAlert(
      'Please check your username and password, and try again.',
      'error',
      'Login Failed',
    )
  }
}

onMounted(checkOidcProvider)
</script>
