<!--
  Bouton Créer du header de l'application et boite de dialogue associée
-->

<template>
  <main>
    <v-btn
      v-if="asIcon"
      :elevation="0"
      class="theme-primary"
      :icon="true"
      size="small"
      @click="show"
    >
      <v-icon>fas fa-plus</v-icon>
    </v-btn>

    <v-btn
      v-else
      :elevation="2"
      height="30"
      class="theme-x-create-btn"
      @click="show"
    >
      <span>{{ $t('create') }}</span>
    </v-btn>

    <LayoutDialog :show="showCreateDialog" :max-width="850">
      <template #dialogType>{{ $t('creative_assistant') }}</template>

      <template #dialogTitle>
        <span v-if="location === 'home'">{{
          $t('what_do_you_want_to_create')
        }}</span>
        <span v-else-if="location === 'access'">{{
          $t('what_type_of_contact_do_you_want_to_create')
        }}</span>
        <span v-else-if="location === 'event'">{{
          $t('what_do_you_want_to_add_to_your_planning')
        }}</span>
        <span v-else-if="location === 'message'">{{
          $t('what_do_you_want_to_send')
        }}</span>
        <span v-else-if="location === 'event-params'">{{
          $t('which_date_and_which_hour')
        }}</span>
      </template>

      <template #dialogText>
        <LayoutHeaderUniversalCreationGenerateCardsSteps
          :path="path"
          @cardClick="onCardClick"
          @urlUpdate="onUrlUpdate"
        />
      </template>

      <template #dialogBtn>
        <div class="text-center">
          <v-btn class="theme-neutral-soft" @click="close">
            {{ $t('cancel') }}
          </v-btn>

          <v-btn
            v-if="path.length > 1"
            class="theme-neutral-soft"
            @click="goToPrevious"
          >
            {{ $t('previous_step') }}
          </v-btn>

          <v-btn
            v-if="targetUrl !== null && !directRedirectionOngoing"
            class="theme-primary"
            @click="validate"
          >
            {{ $t('validate') }}
          </v-btn>
        </div>
      </template>
    </LayoutDialog>
  </main>
</template>

<script setup lang="ts">
import { ref } from '@vue/reactivity'
import type { Ref } from '@vue/reactivity'
import { useDisplay } from 'vuetify'
import type { ComputedRef } from 'vue'
import { usePageStore } from '~/stores/page'

const { mdAndDown: asIcon } = useDisplay()

// Set to true to show the Create dialog
const showCreateDialog: Ref<boolean> = ref(false)

// The succession of menus the user has been through; used to keep track of the navigation
const path: Ref<Array<string>> = ref(['home'])

// The current menu
const location: ComputedRef<string> = computed(() => {
  return path.value.at(-1) ?? 'home'
})

// The current target URL (@see onUrlUpdate())
const targetUrl: Ref<string | null> = ref(null)

// Already redirecting (to avoid the display of the 'validate' button when page has already been redirected and is loading)
const directRedirectionOngoing: Ref<boolean> = ref(false)

/**
 * Return to the home menu
 */
const reset = () => {
  path.value = ['home']
}

/**
 * Go back to the previous step
 */
const goToPrevious = () => {
  if (path.value.length === 1) {
    return
  }
  path.value.pop()
}

/**
 * Display the create dialog
 */
const show = () => {
  reset()
  showCreateDialog.value = true
}

const pageStore = usePageStore()

/**
 * Redirect the user to the given url
 * @param url
 */
const redirect = (url: string) => {
  pageStore.loading = true
  window.location.href = url
}

/**
 * Go to the current targetUrl
 */
const validate = () => {
  if (targetUrl.value === null) {
    console.warn('No url defined')
    return
  }
  redirect(targetUrl.value)
}

/**
 * Close the Create dialog
 */
const close = () => {
  showCreateDialog.value = false
}

/**
 * A cart has been clicked. The reaction depends on the card's properties.
 *
 * @param to  Target location in the wizard
 * @param href  Target absolute url
 */
const onCardClick = (to: string | null, href: string | null) => {
  if (to !== null) {
    // La carte définit une nouvelle destination : on se dirige vers elle.
    path.value.push(to)
  } else if (href !== null) {
    // La carte définit une url avec href, et pas de nouvelle destination : on suit directement le lien pour éviter
    // l'étape de validation devenue inutile.
    directRedirectionOngoing.value = true
    redirect(href)
  } else {
    console.warn('Error: card has no `to` nor `href` defined')
  }
}

/**
 * The url has been updated in the GenerateCardsStep component
 * @param url
 */
const onUrlUpdate = (url: string) => {
  targetUrl.value = url
}
</script>

<style scoped lang="scss">
:deep(.v-btn .v-icon) {
  font-size: 16px !important;
}
:deep(.v-btn) {
  text-transform: none !important;
  font-weight: 600;
}
</style>
