<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 CheckboxWrapper from '@/components/CheckboxWrapper.vue'
import SectionTitle from '@/components/SectionTitle.vue'
import MessageBox from '@/components/MessageBox.vue'
import { MESSAGES } from '@/data/messages'
import { resetAlert } from '@/helpers'
import { useBuildingStore } from '@/stores/buildings'

let timeout = null

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

const buildings = useBuildingStore()

// Initial values
const state = reactive({
  characteristicsComment: null,
  energyPerformanceCertificate: null,
  listedBuilding: null,
  livingSpace: null,
  numberOfFloors: null,
  yearOfConstruction: null
})

const rules = computed(() => {
  return {
    characteristicsComment: {},
    energyPerformanceCertificate: {},
    listedBuilding: {},
    livingSpace: {},
    numberOfFloors: {},
    yearOfConstruction: {}
  }
})

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 response = await buildings.updateBuildingCharacteristics(buildings.active, state)

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

      await buildings.fetchBuildings()
    } else {
      message.value = MESSAGES[response.message]
      messageType.value = 'danger'
    }

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

onMounted(() => {
  if (buildings.current) {
    state.characteristicsComment = buildings.current.data.characteristicsComment
    state.energyPerformanceCertificate = buildings.current.data.energyPerformanceCertificate
    state.listedBuilding = buildings.current.data.listedBuilding
    state.livingSpace = buildings.current.data.livingSpace
    state.numberOfFloors = buildings.current.data.numberOfFloors
    state.yearOfConstruction = buildings.current.data.yearOfConstruction
  }
})

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

<template>
  <div class="form">
    <form @submit.prevent="onSubmit">
      <div class="form-content">
        <SectionTitle value="Gebäudedetails" />
        <InputGroup>
          <label for="characteristic-yoc">Baujahr</label>
          <input class="number" id="characteristic-yoc" type="number" v-model="state.yearOfConstruction" />
        </InputGroup>
        <InputGroup>
          <label for="characteristic-listed">Ist das Gebäude denkmalgeschützt?</label>
          <CheckboxWrapper value="Denkmalschutz liegt vor">
            <input id="characteristic-listed" type="checkbox" v-model="state.listedBuilding" />
          </CheckboxWrapper>
        </InputGroup>
        <InputGroup :row="true">
          <InputGroup>
            <label for="characteristic-floors">Stockwerke</label>
            <InputWrapper>
              <input class="number" id="characteristic-floors" type="number" v-model="state.numberOfFloors" />
              <MessageBox msg="Geben Sie die Anzahl der Vollgeschosse ein" type="basic" />
            </InputWrapper>
          </InputGroup>
          <InputGroup>
            <label for="characteristic-area">Wohnfläche (m²) gesamt</label>
            <input class="number" id="characteristic-area" type="number" v-model="state.livingSpace" />
          </InputGroup>
        </InputGroup>
        <SectionTitle value="Energieeffizienz" />
        <InputGroup>
          <label for="characteristics-cert">Energieeffizienz (kWh/m²)</label>
          <InputWrapper>
            <input class="number" id="characteristics-cert" type="number"
              v-model="state.energyPerformanceCertificate" />
            <MessageBox msg="Sie können den Wert aus dem Energieausweis entnehmen." type="basic" />
          </InputWrapper>
        </InputGroup>
        <InputGroup>
          <label for="characteristic-comment">Zusätzliche Kommentare</label>
          <MessageBox msg="Tragen Sie weitere Informationen zum Gebäude ein." type="basic" />
          <textarea id="characteristic-comment" :rows="5" v-model="state.characteristicsComment" />
        </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>