<script setup lang="ts">
import { getSelectedProfile, ProfileApiClient, type Profile } from '@/api/profile'
import AppButton from '@/components/common/AppButton.vue'
import ConfirmModal from '@/components/common/ConfirmModal.vue'
import HomeModule from '@/components/HomeModule.vue'
import { showAlert } from '@/util/alert'
import { onMounted, ref, useTemplateRef, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()
const confirmDeleteModal = useTemplateRef('confirmDeleteModal')

const profile: Ref<Profile | undefined> = ref()

onMounted(async () => {
  try {
    profile.value = await new ProfileApiClient().getProfile(getSelectedProfile(route))
  } catch (err) {
    console.error(err)
    await showAlert('Failed to get profile.')
    await router.replace('/profiles')
  }
})

async function deleteProfile() {
  const currentProfileName = getSelectedProfile(route)
  if (await confirmDeleteModal.value?.confirm()) {
    const api = new ProfileApiClient()
    try {
      await api.deleteProfile(currentProfileName)
      await router.replace('/profiles')
    } catch (err) {
      console.error(err)
    }
  }
}

async function downloadData() {
  if (!profile.value) return
  const api = new ProfileApiClient()
  await api.downloadData(profile.value.name)
}
</script>
<template>
  <HomeModule
    title="Profile"
    v-if="profile"
  >
    <template v-slot:default>
      <p>
        Your currently selected profile is: <strong>{{ profile.name }}</strong>
      </p>
      <p>
        <AppButton
          size="sm"
          @click="router.push(`/profiles/${profile.name}/vendors`)"
          >Vendors</AppButton
        >
        <AppButton
          size="sm"
          @click="router.push(`/profiles/${profile.name}/categories`)"
          >Categories</AppButton
        >
      </p>

      <ConfirmModal ref="confirmDeleteModal">
        <p>Are you sure you want to delete this profile?</p>
        <p>
          This will permanently remove all data associated with this profile, and this cannot be
          undone!
        </p>
      </ConfirmModal>
    </template>
    <template v-slot:actions>
      <AppButton
        icon="folder-open"
        @click="router.push('/profiles')"
        >Choose another profile</AppButton
      >
      <AppButton
        icon="download"
        @click="downloadData()"
        size="sm"
        >Download Data</AppButton
      >
      <AppButton
        button-style="secondary"
        icon="trash"
        @click="deleteProfile()"
        size="sm"
        >Delete</AppButton
      >
    </template>
  </HomeModule>
</template>
