﻿<script setup>
import {computed, ref, watch} from 'vue'
import {useUserProfileStore} from "@/stores/userProfileStore.js";
import {useCreatorProfileStore} from "@/stores/creatorProfileStore.js";
import {useClient} from "@/plugins/api.js";
import {useRouter} 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 creatorProfileStore = useCreatorProfileStore();
const userProfileStore = useUserProfileStore();

function handleCreatorNameReservationIdChanged($event) {
  console.log(`in handleCreatorNameReservationIdChanged: ${$event.value}`);
  creatorNameReservationId.value = $event.value
}

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.fetchCurrentCreatorProfile();
    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="create-creator-card">

    <div class="py-2 text-3xl font-bold text-center mb-10">
      Créez votre Hutopy.
    </div>

    <div class="flex flex-column justify-end gap-2">
      <v-alert
          v-if="!!errorMessage"
          outlined
          type="error"
      >
        {{ errorMessage }}
      </v-alert>

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

      <div class="flex flex-row justify-end gap-2">
        <v-btn
            :disabled="!canSave"
            variant="outlined"
            @click="createAccount"
            :style="{ borderColor: 'rgb(159, 76, 173)', color: 'rgb(159, 76, 173)' }"
        >
          Créer
        </v-btn>
      </div>

    </div>
  </div>
</template>

<style scoped>
.create-creator-card {
  @apply text-center max-w-[1000px] mx-auto p-10 bg-white shadow-2xl rounded mt-16 ;
}

</style>