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

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

onMounted(async () => {
  authStore.$subscribe(async (_, state) => {
    if (state.state === null) {
      await router.replace('/login')
    }
  })

  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) {
  profileStore.onProfileSelected(profile)
  router.push('/profiles/' + profile.name)
}

async function addProfile() {
  try {
    const api = new ProfileApiClient()
    api.createProfile(newProfileName.value)
    newProfileName.value = ''
    addProfileModal.value?.close()
    await fetchProfiles()
  } 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 class="profile-card" @click="addProfileModal?.show()">
      <span>Add a new profile...</span>
    </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-secondary);
  border-radius: 1em;
  margin-top: 1em;
  margin-bottom: 1em;
  cursor: pointer;
}

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