﻿<script setup>
import {computed, ref} from 'vue'
import {useUserProfileStore} from "@/stores/userProfileStore.js";
import {useCreatorProfileStore} from "@/stores/creatorProfileStore.js";
import {useClient} from "@/plugins/api.js";
import {useRouter, useRoute} from "vue-router";
import NameEditor from "@/views/creators/NameEditor.vue";

const creatorName = ref('');
const creatorNameReservationId = ref(undefined);
const canSave = computed(() => creatorNameReservationId.value !== undefined)

const isOperationPending = ref(false);
const errorMessage = ref('');

const router = useRouter();
const route = useRoute();
const creatorProfileStore = useCreatorProfileStore();
const userProfileStore = useUserProfileStore();

function handleCreatorNameReservationIdChanged($event) {
  creatorNameReservationId.value = $event.value
}

function cancel () {
  // if a returnUrl query‑string was supplied, prefer it
  const returnUrl = route.query.returnUrl
  if (typeof returnUrl === 'string' && returnUrl.length) {
    router.push(returnUrl)
    return
  }

  // otherwise just go back one step in history
  router.back()
}

// TODO: The `fetchCreatorProfile` function should be private (push-up to the store)!
async function createAccount() {
  try {
    isOperationPending.value = true;
    const client = useClient();
    errorMessage.value = '';
    await client.post('/api/creators', {
      creatorId: userProfileStore.user.id,
      slugReservationId: creatorNameReservationId.value,
    });
    await creatorProfileStore.fetchCreatorProfile();
    await router.push(`/@${creatorProfileStore.creator.name}`);
  } catch (error) {
    if (error?.response?.data?.errors) {
      errorMessage.value = error.response.data.errors[0]?.['reason'] || 'An unexpected error occurred.';
    } else {
      errorMessage.value = error?.response?.data?.message || error.message || 'An unexpected error occurred.';
    }
  } finally {
    isOperationPending.value = false;
  }
}

</script>

<template>
  <div class="container">
    <div class="card">

      <div class="card-title">
        Créez votre Hutopy.
      </div>

      <div class="card-content">
        <name-editor
            v-model:name="creatorName"
            creator-name-reservation-id="creatorNameDirty"
            @update:creator-name-reservation-id="handleCreatorNameReservationIdChanged($event)"
        ></name-editor>
      </div>

      <div class="card-actions">
        <button
            class="secondary"
            @click="cancel">
          Cancel
        </button>
        <button
            class="primary"
            :disabled="!canSave"
            @click="createAccount">
          Créer
        </button>
      </div>

    </div>
  </div>

  <v-alert
      v-if="!!errorMessage"
      outlined
      type="error"
  >
    {{ errorMessage }}
  </v-alert>


</template>

<style scoped>

.container {
  @apply min-h-screen w-full;
  @apply flex items-center justify-center;
}

</style>