<script setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import useVuelidate from '@vuelidate/core'
import { required } from '@vuelidate/validators'

import InputGroup from '@/components/InputGroup.vue'
import InputWrapper from '@/components/InputWrapper.vue'
import MessageBox from '@/components/MessageBox.vue'
import SectionTitle from '@/components/SectionTitle.vue'
import { MESSAGES } from '@/data/messages'
import { randomPrefix, resetAlert } from '@/helpers'
import { useBuildingStore } from '@/stores/buildings'

let timeout = null

const emit = defineEmits(['closeModal', 'setupCompleted'])

const message = ref(null)
const messageType = ref(null)

const buildings = useBuildingStore()

const state = reactive({
  buildingCity: '',
  buildingGmlId: null,
  buildingName: '',
  buildingPrefix: null,
  buildingStreetName: '',
  buildingStreetNumber: '',
  buildingZipcode: ''
})

const rules = computed(() => {
  return {
    buildingCity: {},
    buildingGmlId: {},
    buildingName: { required },
    buildingPrefix: { required },
    buildingStreetName: {},
    buildingStreetNumber: {},
    buildingZipcode: {}
  }
})

const v$ = useVuelidate(rules, state)

async function onSubmit() {
  try {
    clearTimeout(timeout)
    message.value = null

    const isValid = await v$.value.$validate()

    if (!isValid) {
      message.value = MESSAGES['INVALID_INPUT']
      messageType.value = 'warning'

      timeout = resetAlert(message)

      return
    }

    const { buildingCity, buildingGmlId, buildingName, buildingPrefix, buildingStreetName, buildingStreetNumber, buildingZipcode } = state
    const response = await buildings.updateBuilding(buildings.firstBuilding._id, {
      buildingPrefix,
      buildingName,
      buildingAddress: [buildingStreetName, buildingStreetNumber, buildingZipcode, buildingCity].join('::'),
      buildingGmlId
    })

    if (response.success) {
      await buildings.fetchBuildings()

      buildings.setActiveBuilding(buildings.firstBuilding._id)

      emit('closeModal')
      emit('setupCompleted')
    } else {
      message.value = MESSAGES[response.message]
      messageType.value = 'danger'
    }

    timeout = resetAlert(message)
  } catch (error) {
    console.error('ERROR:', error.name)
  }
}

onMounted(() => {
  state.buildingPrefix = randomPrefix()
})

onUnmounted(() => {
  clearTimeout(timeout)
})
</script>

<template>
  <div class="initial-setup">
    <form @submit.prevent="onSubmit" class="initial-setup__form">
      <div class="form-content">
        <SectionTitle value="Stammdaten" />
        <InputGroup :row="true">
          <InputGroup>
            <label for="setup-user">Kennung</label>
            <input id="setup-user" type="text" v-model="state.buildingPrefix" />
          </InputGroup>
          <InputGroup :stretch="true">
            <label for="setup-user">Gebäudebezeichnung</label>
            <input id="setup-user" type="text" v-model="state.buildingName" />
          </InputGroup>
        </InputGroup>
        <MessageBox
          msg="Sie müssen eine Kennung wählen. Nehmen Sie zum Beispiel die ersten Buchstaben der Adresse oder wählen Sie eine beliebige Kombination. 4 bis 5 Zeichen sind empfohlen. Bitte beachten Sie, dass diese Kennung nicht mehr geändert werden kann."
          type="basic" />
        <InputGroup :row="true">
          <InputGroup :stretch="true">
            <label for="setup-user">Straße</label>
            <input id="setup-user" type="text" v-model="state.buildingStreetName" />
          </InputGroup>
          <InputGroup>
            <label for="setup-user">Hausnummer</label>
            <input id="setup-user" type="text" v-model="state.buildingStreetNumber" />
          </InputGroup>
        </InputGroup>
        <InputGroup :row="true">
          <InputGroup>
            <label for="setup-user">Postleitzahl</label>
            <input id="setup-user" type="text" v-model="state.buildingZipcode" />
          </InputGroup>
          <InputGroup :stretch="true">
            <label for="setup-user">Stadt</label>
            <input id="setup-user" type="text" v-model="state.buildingCity" />
          </InputGroup>
        </InputGroup>
        <SectionTitle value="Optional" />
        <InputGroup>
          <label for="setup-user">GML Id</label>
          <InputWrapper>
            <input id="setup-user" type="text" v-model="state.buildingGmlId" />
            <MessageBox msg="Sie können die GML Id aus dem Crowdsourcing Tool (CS-T) beziehen." type="basic" />
          </InputWrapper>
        </InputGroup>
      </div>
      <div class="form-section">
        <MessageBox v-if="message" :msg="message" :type="messageType" />
        <button class="button primary" type="submit" :disabled="message">
          <span>Speichern</span>
        </button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.initial-setup {
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.initial-setup__form {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>