<script setup lang="ts">
import { AuthApiClient } from '@/api/auth'
import { ApiError } from '@/api/base'
import AppButton from '@/components/common/AppButton.vue'
import AppPage from '@/components/common/AppPage.vue'
import AppForm from '@/components/common/form/AppForm.vue'
import FormControl from '@/components/common/form/FormControl.vue'
import FormGroup from '@/components/common/form/FormGroup.vue'
import ModalWrapper from '@/components/common/ModalWrapper.vue'
import { LogoutReason, useAuthStore } from '@/stores/auth-store'
import { showAlert, showConfirm } from '@/util/alert'
import { hideLoader, showLoader } from '@/util/loader'
import { ref, useTemplateRef } from 'vue'

const authStore = useAuthStore()

const changePasswordModal = useTemplateRef('changePasswordModal')
const currentPassword = ref('')
const newPassword = ref('')

async function doDeleteUser() {
  if (
    await showConfirm(
      'Are you sure you want to delete your account? All data will be permanently deleted.',
    )
  ) {
    const api = new AuthApiClient()
    try {
      await api.deleteMyUser()
      await showAlert('Your user has been deleted. You will now be logged out.')
      authStore.onUserLoggedOut(LogoutReason.USER_LOGGED_OUT)
    } catch (err) {
      console.error(err)
    }
  }
}

async function showChangePasswordModal() {
  await changePasswordModal.value?.show()
  // Reset password vars to avoid data leakage.
  currentPassword.value = ''
  newPassword.value = ''
}

async function doChangePassword() {
  changePasswordModal.value?.close()
  showLoader()
  const api = new AuthApiClient()
  try {
    await api.changeMyPassword(currentPassword.value, newPassword.value)
    hideLoader()
    await showAlert('Password has been updated.')
  } catch (err) {
    hideLoader()
    console.error(err)
    if (err instanceof ApiError) {
      await showAlert(err.message)
    }
  }
}
</script>
<template>
  <AppPage title="My User">
    <p>
      You are logged in as <code style="font-size: 14px">{{ authStore.state?.username }}</code
      >.
    </p>
    <p>
      There's not really that much to do with your user account specifically, all important settings
      are profile-specific.
    </p>
    <div style="text-align: right">
      <AppButton @click="showChangePasswordModal()">Change Password</AppButton>
      <AppButton
        icon="trash"
        theme="secondary"
        @click="doDeleteUser()"
        >Delete My User</AppButton
      >
    </div>

    <!-- Modal for changing the user's password. -->
    <ModalWrapper ref="changePasswordModal">
      <template v-slot:default>
        <AppForm>
          <h2>Change Password</h2>
          <p>Change the password used to log into your user account.</p>
          <FormGroup>
            <FormControl label="Current Password">
              <input
                type="password"
                v-model="currentPassword"
                minlength="8"
              />
            </FormControl>
          </FormGroup>
          <FormGroup>
            <FormControl label="New Password">
              <input
                type="password"
                v-model="newPassword"
                minlength="8"
                @keydown.enter.prevent="doChangePassword()"
              />
            </FormControl>
          </FormGroup>
        </AppForm>
      </template>
      <template v-slot:buttons>
        <AppButton @click="doChangePassword()">Change</AppButton>
        <AppButton
          theme="secondary"
          @click="changePasswordModal?.close()"
          >Cancel</AppButton
        >
      </template>
    </ModalWrapper>
  </AppPage>
</template>
