<script setup lang="ts">
import { ProfileApiClient, type Profile } from '@/api/profile'
import AppButton from '@/components/common/AppButton.vue'
import AppPage from '@/components/common/AppPage.vue'
import ModalWrapper from '@/components/common/ModalWrapper.vue'
import { onMounted, type Ref, ref, useTemplateRef } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

const profiles: Ref<Profile[]> = ref([])
const addProfileModal = useTemplateRef('addProfileModal')
const newProfileName = ref('')

onMounted(async () => {
  await fetchProfiles()
})

async function fetchProfiles() {
  const client = new ProfileApiClient()
  try {
    profiles.value = (await client.getProfiles()).sort((a, b) => a.name.localeCompare(b.name))
  } catch {
    profiles.value = []
  }
}

function selectProfile(profile: Profile) {
  router.push('/profiles/' + profile.name)
}

async function addProfile() {
  try {
    const api = new ProfileApiClient()
    const newProfile = await api.createProfile(newProfileName.value)
    newProfileName.value = ''
    addProfileModal.value?.close()
    await router.push('/profiles/' + newProfile.name)
  } catch (err) {
    console.error(err)
  }
}
</script>
<template>
  <AppPage title="Select a Profile">
    <div
      class="profile-card"
      v-for="profile in profiles"
      :key="profile.name"
      @click="selectProfile(profile)"
    >
      <span>{{ profile.name }}</span>
    </div>
    <div style="text-align: right">
      <AppButton
        icon="plus"
        @click="addProfileModal?.show()"
        >Add a new profile</AppButton
      >
    </div>

    <ModalWrapper ref="addProfileModal">
      <template v-slot:default>
        <h3 class="app-modal-dialog-header">Add Profile</h3>
        <div>
          <label for="new-profile-name-input">Enter the name of your new profile.</label>
          <input
            type="text"
            minlength="3"
            id="new-profile-name-input"
            v-model="newProfileName"
          />
        </div>
      </template>
      <template v-slot:buttons>
        <AppButton @click="addProfile()">Add</AppButton>
        <AppButton
          button-style="secondary"
          @click="addProfileModal?.close()"
          >Cancel</AppButton
        >
      </template>
    </ModalWrapper>
  </AppPage>
</template>
<style lang="css">
.profile-card {
  display: flex;
  justify-content: space-between;
  padding: 0.5em;
  background-color: var(--bg);
  border-radius: 1em;
  margin-top: 1em;
  margin-bottom: 1em;
  cursor: pointer;
}

.profile-card:hover {
  background-color: var(--bg-darker);
}
</style>
