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

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

let timeout = null

const emit = defineEmits(['closeModal'])

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

const buildings = useBuildingStore()

// Initial values
const state = reactive({
  buildingPrefix: null,
  buildingName: null,
  buildingStreetName: null,
  buildingStreetNumber: null,
  buildingZipcode: null,
  buildingCity: null
})

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

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 { buildingPrefix, buildingName, buildingStreetName, buildingStreetNumber, buildingZipcode, buildingCity } = state
    const response = await buildings.createBuilding({
      buildingPrefix,
      buildingName,
      buildingAddress: [buildingStreetName, buildingStreetNumber, buildingZipcode, buildingCity].join('::')
    })

    if (response.success) {
      message.value = MESSAGES[response.message]
      messageType.value = 'success'

      await buildings.fetchBuildings()

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

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

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

<template>
  <div class="form">
    <form @submit.prevent="onSubmit">
      <div class="form-content">
        <SectionTitle value="Stammdaten" />
        <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>
            <label for="bf-prefix">Kennung</label>
            <input id="bf-prefix" type="text" v-model="state.buildingPrefix" />
          </InputGroup>
          <InputGroup :stretch="true">
            <label for="bf-name">Gebäudebezeichnung</label>
            <input id="bf-name" type="text" v-model="state.buildingName" />
          </InputGroup>
        </InputGroup>
        <InputGroup :row="true">
          <InputGroup :stretch="true">
            <label for="bf-street-name">Straße</label>
            <input id="bf-street-name" type="text" v-model="state.buildingStreetName" />
          </InputGroup>
          <InputGroup>
            <label for="bf-street-number">Hausnummer</label>
            <input id="bf-street-number" type="text" v-model="state.buildingStreetNumber" />
          </InputGroup>
        </InputGroup>
        <InputGroup :row="true">
          <InputGroup>
            <label for="bf-zipcode">Postleitzahl</label>
            <input id="bf-zipcode" type="text" v-model="state.buildingZipcode" />
          </InputGroup>
          <InputGroup :stretch="true">
            <label for="bf-city">Stadt</label>
            <input id="bf-city" type="text" v-model="state.buildingCity" />
          </InputGroup>
        </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>