﻿<script setup>
import {ref} 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";

const creatorName = ref('');
const errorMessage = ref('');
const isLoading = ref(false);

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

async function createAccount() {
  const client = useClient();
  try {
    errorMessage.value = '';
    isLoading.value = true;
    const normalizedCreatorName = creatorName.value.toLowerCase();
    await client.post('/api/creators', {
      creatorId: userProfileStore.user.id,
      name: normalizedCreatorName,
    });
    await creatorProfileStore.fetchCurrentCreatorProfile();
    await router.push(`/@${normalizedCreatorName}`);
  } 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 {
    isLoading.value = false;
  }
}
</script>

<template>
  <div>
    <div class="create-creator-card">
    <div class="py-2 text-3xl font-bold">
      <div class="text-center mb-10">Créez votre Hutopy.</div>
    </div>
    <div class="flex flex-column justify-end gap-2">
      <v-alert
          v-if="!!errorMessage"
          dense
          outlined
          text
          type="error"
      >
        {{ errorMessage }}
      </v-alert>

      <v-text-field
          variant="outlined"
          v-model="creatorName"
          label="Nom de la page"
          outlined
      ></v-text-field>
      <div class="flex flex-row justify-end gap-2">

        <v-btn
            :disabled="isLoading"
            variant="outlined"
            @click="createAccount"
            :style="{ borderColor: 'rgb(159, 76, 173)', color: 'rgb(159, 76, 173)' }"
        >
          Créer
        </v-btn>
      </div>
    </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>