<template>
  <LayoutCommonSection>
    <v-row>
      <v-col cols="12" sm="12">
        <h4 class="mb-8">{{ $t('general_informations') }}</h4>

        <UiInputText
          v-model="proxyEntity.name"
          field="name"
          :rules="getAsserts('name')"
        />

        <span class="label">{{ $t('datetimeStart') }}</span>
        <UiInputDateTimePicker
          :model-value="proxyEntity.datetimeStart"
          field="datetimeStart"
          label="datetimeStart"
          :with-time-picker="true"
          class="my-2"
          :rules="getAsserts('datetimeStart')"
          validate-on-blur
          @update:model-value="onUpdateDateTimeStart(proxyEntity, $event)"
        />

        <span class="label">{{ $t('datetimeEnd') }}</span>
        <UiInputDateTimePicker
          :model-value="proxyEntity.datetimeEnd"
          field="datetimeEnd"
          label="datetimeEnd"
          :with-time-picker="true"
          class="my-2"
          :rules="getAsserts('datetimeEnd')"
          @update:model-value="onUpdateDateTimeEnd(proxyEntity, $event)"
        />

        <span class="label">{{ $t('description') }}</span>
        <UiInputTextArea v-model="proxyEntity.description" class="mt-3" />

        <UiInputTreeSelectEventCategories
          v-model="proxyEntity.categories"
          label="event_categories_choices"
        />

        <UiInputImage
          v-model="proxyEntity.image"
          field="image"
          :width="240"
          :cropping-enabled="true"
        />
      </v-col>
    </v-row>
  </LayoutCommonSection>

  <LayoutCommonSection>
    <v-row>
      <v-col cols="12">
        <h4 class="mb-8">{{ $t('place_event') }}</h4>

        <UiInputAutocompleteApiResources
          v-if="!newPlace"
          :model-value="proxyEntity.place"
          field="place"
          :model="PlaceSearchItem"
          list-value="id"
          list-label="name"
          @update:model-value="getPlace(proxyEntity)"
        />

        <v-row v-if="!newPlace" class="mb-6 justify-center">
          <v-col
            v-if="proxyEntity.place && !editPlace"
            cols="12"
            sm="6"
            class="d-flex justify-center mb-2"
          >
            <v-btn
              prepend-icon="fa-solid fa-pencil"
              @click="onEditPlaceClick(proxyEntity)"
            >
              {{ $t('edit_place') }}
            </v-btn>
          </v-col>

          <v-col cols="12" sm="6" class="d-flex justify-center mb-2">
            <v-btn
              prepend-icon="fa-solid fa-plus"
              @click="onAddPlaceClick(proxyEntity)"
            >
              {{ $t('add_place') }}
            </v-btn>
          </v-col>
        </v-row>

        <UiInputText
          v-model="proxyEntity.placeName"
          :readonly="!newPlace && !editPlace"
          field="placeName"
        />

        <UiInputText
          v-model="proxyEntity.streetAddress"
          :readonly="!newPlace && !editPlace"
          field="streetAddress"
        />

        <UiInputText
          v-model="proxyEntity.streetAddressSecond"
          :readonly="!newPlace && !editPlace"
          field="streetAddressSecond"
        />

        <UiInputText
          v-model="proxyEntity.streetAddressThird"
          :readonly="!newPlace && !editPlace"
          field="streetAddressThird"
        />

        <UiInputText
          v-model="proxyEntity.postalCode"
          :readonly="!newPlace && !editPlace"
          field="postalCode"
        />

        <UiInputText
          v-model="proxyEntity.addressCity"
          :readonly="!newPlace && !editPlace"
          field="addressCity"
        />

        <UiInputAutocompleteApiResources
          v-model="proxyEntity.addressCountry"
          :readonly="!newPlace && !editPlace"
          field="addressCountry"
          :model="Country"
          list-value="id"
          list-label="name"
        />

        <client-only>
          <UiMapLeaflet
            v-model:latitude="proxyEntity.latitude"
            v-model:longitude="proxyEntity.longitude"
            :readonly="!newPlace && !editPlace"
            :street-address="proxyEntity.streetAddress"
            :street-address-second="proxyEntity.streetAddressSecond"
            :street-address-third="proxyEntity.streetAddressThird"
            :postal-code="proxyEntity.postalCode"
            :address-city="proxyEntity.addressCity"
            :address-country-id="proxyEntity.addressCountry"
            :search-button="true"
          ></UiMapLeaflet>
        </client-only>
      </v-col>
    </v-row>
  </LayoutCommonSection>

  <LayoutCommonSection>
    <v-row>
      <v-col cols="12">
        <h4 class="mb-8">{{ $t('communication_params') }}</h4>

        <UiInputText v-model="proxyEntity.url" field="url" />

        <UiInputAutocompleteEnum
          v-model="proxyEntity.pricing"
          enum-name="pricing_event"
          field="pricing"
        />

        <UiInputText
          v-if="proxyEntity.pricing === 'PAID'"
          v-model="proxyEntity.urlTicket"
          field="urlTicket"
        />

        <UiInputNumber
          v-if="proxyEntity.pricing === 'PAID'"
          v-model="proxyEntity.priceMini"
          field="priceMini"
        />

        <UiInputNumber
          v-if="proxyEntity.pricing === 'PAID'"
          v-model="proxyEntity.priceMaxi"
          field="priceMaxi"
        />
      </v-col>
    </v-row>
  </LayoutCommonSection>

  <LazyLayoutDialog :show="showAlert" theme="warning">
    <template #dialogType>{{ $t('important') }}</template>
    <template #dialogTitle>{{ $t('place_change_everywhere') }}</template>
    <template #dialogText>
      <v-card-text class="text">
        <p>
          {{ $t('warning_edit_place') }}
        </p>
      </v-card-text>
    </template>
    <template #dialogBtn>
      <v-btn class="mr-4 submitBtn theme-neutral-strong" @click="closeDialog">
        {{ $t('cancel') }}
      </v-btn>
      <v-btn class="mr-4 submitBtn theme-warning" @click="onEditPlaceConfirm">
        {{ $t('i_understand') }}
      </v-btn>
    </template>
  </LazyLayoutDialog>
</template>

<script setup lang="ts">
import Event from '~/models/Freemium/Event'
import Place from '~/models/Freemium/Place'
import { getAssertUtils } from '~/services/asserts/getAssertUtils'
import DateUtils from '~/services/utils/dateUtils'
import Country from '~/models/Core/Country'
import PlaceSearchItem from '~/models/Custom/Search/PlaceSearchItem'
import { useEntityManager } from '~/composables/data/useEntityManager'

const props = defineProps<{
  entity: Event
}>()

const { em } = useEntityManager()
const getAsserts = (key) => getAssertUtils(Event.getAsserts(), key)

const emit = defineEmits(['update:entity'])

// Pour éviter l'erreur eslint "Unexpected mutation of "modelValue" prop"
const proxyEntity = computed({
  get: () => props.entity,
  set: (value) => emit('update:entity', value),
})

/**
 * Si la date de début est mise à jour, on s'assure que la date de fin est
 * après elle, sinon elle devient égale
 * @param entity
 * @param dateTime
 */
const onUpdateDateTimeStart = (entity, dateTime) => {
  if (DateUtils.isBefore(props.entity.datetimeEnd, dateTime, false)) {
    entity.datetimeEnd = dateTime
  }
  entity.datetimeStart = dateTime
  emit('update:entity', entity)
}

/**
 * Si la date de fin est mise à jour, on s'assure que la date de début est
 * avant elle, sinon elle devient égale
 * @param entity
 * @param dateTime
 */
const onUpdateDateTimeEnd = (entity, dateTime) => {
  if (DateUtils.isBefore(dateTime, props.entity.datetimeStart, false)) {
    entity.datetimeStart = dateTime
  }
  entity.datetimeEnd = dateTime
  emit('update:entity', entity)
}

const showAlert: Ref<boolean> = ref(false)
const newPlace: Ref<boolean> = ref(false)
const editPlace: Ref<boolean> = ref(false)

/**
 * Si on clique sur le bouton "Ajouter un lieu", le choix dans la liste déroulante
 * est mise à nulle, et les champs input de l'adresse sont vidées
 * @param entity
 */
const onAddPlaceClick = function (entity: Event) {
  newPlace.value = true
  entity.place = null
  resetPlace(entity)
}

/**
 * Quand on clique sur le bouton "Editer le lieu", une alerte s'affiche.
 */
const onEditPlaceClick = function () {
  showAlert.value = true
}

/**
 * Quand on ferme la boite de dialogue
 */
const closeDialog = function () {
  showAlert.value = false
}

/**
 * Si on décide d'éditer le lieu
 */
const onEditPlaceConfirm = function () {
  showAlert.value = false
  editPlace.value = true
}

/**
 * Lorsque l'on choisit un lieu dans la liste déroulante, on met à jour les champs
 * input de l'adresse
 * @param entity
 */
const getPlace = async (entity: Event) => {
  if (entity.place) {
    const placeInstance = await em.fetch(Place, entity.place as number)
    entity.placeName = placeInstance.name
    entity.streetAddress = placeInstance.streetAddress
    entity.streetAddressSecond = placeInstance.streetAddressSecond
    entity.streetAddressThird = placeInstance.streetAddressThird
    entity.addressCity = placeInstance.addressCity
    entity.postalCode = placeInstance.postalCode
    entity.addressCountry = placeInstance.addressCountry
    entity.latitude = placeInstance.latitude
    entity.longitude = placeInstance.longitude
    editPlace.value = false
  } else {
    // Dans le cas où l'on ne récupère aucune place on remet à null le formulaire de l'adresse
    resetPlace(entity)
  }

  emit('update:entity', entity)
}

/**
 * fonction permettant de remettre à vide tous les champs input de l'adresse
 * @param entity
 */
const resetPlace = (entity: Event) => {
  entity.placeName = null
  entity.streetAddress = null
  entity.streetAddressSecond = null
  entity.streetAddressThird = null
  entity.addressCity = null
  entity.postalCode = null
  entity.addressCountry = null
  entity.latitude = null
  entity.longitude = null
}

// Nettoyer les données lors du démontage du composant
onBeforeUnmount(() => {
  // Nettoyer les références du store si nécessaire
  if (import.meta.client) {
    clearNuxtData('/^' + Place.entity + '_/')
    useRepo(Place).flush()
  }
})
</script>

<style scoped lang="scss">
.label {
  font-size: 16px;
  color: rgb(var(--v-theme-on-primary-alt));
}
</style>
