<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 { resetAlert } from '@/helpers'
import { WINDOW_CONDITION_OPTIONS, WINDOW_FRAME_OPTIONS, WINDOW_GLAZING_OPTIONS } from '@/data/options'
import { useApartmentStore } from '@/stores/apartments'

let timeout = null

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

const apartments = useApartmentStore()

// Initial values
const state = reactive({
  averageWindowAge: null,
  averageWindowCondition: null,
  largeWindows: null,
  mediumWindows: null,
  roofWindows: null,
  smallWindows: null,
  windowComment: null,
  windowFrame: null,
  windowGlazing: null
})

const rules = computed(() => {
  return {
    averageWindowAge: { required },
    averageWindowCondition: { required },
    largeWindows: {},
    mediumWindows: {},
    roofWindows: {},
    smallWindows: {},
    windowComment: {},
    windowFrame: {},
    windowGlazing: { required }
  }
})

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 apartments.updateApartmentWindows(apartments.active, state)

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

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

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

onMounted(() => {
  if (apartments.current) {
    state.averageWindowAge = apartments.current.data.averageWindowAge
    state.averageWindowCondition = apartments.current.data.averageWindowCondition
    state.largeWindows = apartments.current.data.largeWindows
    state.mediumWindows = apartments.current.data.mediumWindows
    state.roofWindows = apartments.current.data.roofWindows
    state.smallWindows = apartments.current.data.smallWindows
    state.windowComment = apartments.current.data.windowComment
    state.windowFrame = apartments.current.data.windowFrame
    state.windowGlazing = apartments.current.data.windowGlazing
  }
})

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

<template>
  <div class="form">
    <form @submit.prevent="onSubmit">
      <div class="form-content">
        <SectionTitle value="Art der Fenster" />
        <InputGroup :row="true">
          <InputWrapper>
            <InputGroup>
              <label for="window-small">Klein (bis 1 m²)</label>
              <input class="number" id="window-small" type="number" v-model="state.smallWindows" />
            </InputGroup>
          </InputWrapper>
        </InputGroup>
        <InputGroup :row="true">
          <InputWrapper>
            <InputGroup>
              <label for="window-medium">Normal (1-2 m²)</label>
              <input class="number" id="window-medium" type="number" v-model="state.mediumWindows" />
            </InputGroup>
          </InputWrapper>
        </InputGroup>
        <InputGroup :row="true">
          <InputWrapper>
            <InputGroup>
              <label for="window-large">Groß (ab 2 m²)</label>
              <input class="number" id="window-large" type="number" v-model="state.largeWindows" />
            </InputGroup>
          </InputWrapper>
        </InputGroup>
        <InputGroup :row="true">
          <InputWrapper>
            <InputGroup>
              <label for="window-roof">Dach (1-2 m²)</label>
              <input class="number" id="window-roof" type="number" v-model="state.roofWindows" />
            </InputGroup>
          </InputWrapper>
        </InputGroup>
        <InputGroup :row="true">
          <InputGroup>
            <label for="window-frame">Rahmenart</label>
            <select id="window-frame" v-model="state.windowFrame">
              <option disabled>Bitte wählen</option>
              <option v-for="option in WINDOW_FRAME_OPTIONS" :value="option.value" :key="option.value">
                {{ option.name }}
              </option>
            </select>
          </InputGroup>
          <InputGroup>
            <label for="window-glazing">Verglasung</label>
            <select id="window-glazing" v-model="state.windowGlazing">
              <option disabled>Bitte wählen</option>
              <option v-for="option in WINDOW_GLAZING_OPTIONS" :value="option.value" :key="option.value">
                {{ option.name }}
              </option>
            </select>
          </InputGroup>
        </InputGroup>
        <InputGroup :row="true">
          <InputGroup>
            <label for="window-condition">Zustand</label>
            <select id="window-condition" v-model="state.averageWindowCondition">
              <option disabled>Bitte wählen</option>
              <option v-for="option in WINDOW_CONDITION_OPTIONS" :value="option.value" :key="option.value">
                {{ option.name }}
              </option>
            </select>
          </InputGroup>
          <InputGroup>
            <label for="window-age">Durchschnittliches Fensteralter</label>
            <input class="number" id="window-age" type="number" v-model="state.averageWindowAge" />
          </InputGroup>
        </InputGroup>
        <InputGroup>
          <label for="window-comment">Zusätzliche Kommentare</label>
          <MessageBox msg="Tragen Sie weitere Informationen zu den Fenstern ein." type="basic" />
          <textarea id="window-comment" :rows="5" v-model="state.windowComment" />
        </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>