<template>
  <Form v-if="userData === null || !userData.authenticated" v-slot="$form" @submit="onFormSubmit">
    <div class="flex flex-column">
      <InputText name="username" type="text" placeholder="Username" fluid />
      <Password name="password" placeholder="Password" :feedback="false" fluid />
      <Button type="submit" label="Log In" />
    </div>
  </Form>

  <div v-if="userData !== null && userData.authenticated">
    <div>Logged in as: {{ userData.is_admin ? 'Admin' : '' }} {{ userData.username }}</div>
    <Form v-slot="$form" @submit="onResetPassword">
      <Password name="password" placeholder="Password" :feedback="false" fluid />
      <Button type="submit" label="Reset Password" fluid />
    </Form>
    <Button @click="onLogout()" label="Log Out" fluid />
  </div>
</template>

<style></style>

<script setup lang="ts">
import { Form } from '@primevue/forms'
import InputText from 'primevue/inputtext'
import Button from 'primevue/button'
import Password from 'primevue/password'
import { useUserData, login, logout, resetPassword } from './user'

const emit = defineEmits<{
  (e: 'onAction'): void
}>()

const userData = useUserData()

function onFormSubmit(form: any) {
  const username = form.values.username
  const password = form.values.password
  login(username, password)
  emit('onAction')
}

function onResetPassword(form: any) {
  const password = form.values.password
  resetPassword(password)
  emit('onAction')
}

function onLogout() {
  logout()
  emit('onAction')
}
</script>
