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

import CheckboxWrapper from '@/components/CheckboxWrapper.vue'
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 { BUILDING_MATERIAL_OPTIONS, INSULATING_MATERIAL_OPTIONS } from '@/data/options'
import { useBuildingStore } from '@/stores/buildings'

let timeout = null

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

const buildings = useBuildingStore()

// Initial values
const state = reactive({
  buildingStructure: null,
  buildingStructureThickness: null,
  facadeEast: true,
  facadeInsulatingMaterial: null,
  facadeInsulatingMaterialThickness: null,
  facadeNorth: true,
  facadeRefurbishmentComment: '',
  facadeSouth: true,
  facadeWest: true
})

const rules = computed(() => {
  return {
    buildingStructure: {},
    buildingStructureThickness: {},
    facadeEast: {},
    facadeInsulatingMaterial: {},
    facadeInsulatingMaterialThickness: {},
    facadeNorth: {},
    facadeRefurbishmentComment: {},
    facadeSouth: {},
    facadeWest: {}
  }
})

const v$ = useVuelidate(rules, state)

function resetInsulatedSides() {
  if (!state.facadeInsulatingMaterial) {
    state.facadeEast = false
    state.facadeNorth = false
    state.facadeSouth = false
    state.facadeWest = false
  } else {
    state.facadeEast = true
    state.facadeNorth = true
    state.facadeSouth = true
    state.facadeWest = true
  }
}

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 { facadeInsulatingMaterial, facadeInsulatingMaterialThickness } = state
    const requestData = {
      ...state,
      facadeInsulatingMaterialThickness: facadeInsulatingMaterial ? facadeInsulatingMaterialThickness : null
    }
    const response = await buildings.updateBuildingFacade(buildings.active, requestData)

    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)
  }
}

onMounted(() => {
  if (buildings.current) {
    state.buildingStructure = buildings.current.data.buildingStructure
    state.buildingStructureThickness = buildings.current.data.buildingStructureThickness
    state.facadeEast = buildings.current.data.facadeEast || true
    state.facadeInsulatingMaterial = buildings.current.data.facadeInsulatingMaterial
    state.facadeInsulatingMaterialThickness = buildings.current.data.facadeInsulatingMaterialThickness
    state.facadeNorth = buildings.current.data.facadeNorth || true
    state.facadeRefurbishmentComment = buildings.current.data.facadeRefurbishmentComment
    state.facadeSouth = buildings.current.data.facadeSouth || true
    state.facadeWest = buildings.current.data.facadeWest || true
  }
})

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

<template>
  <div class="form">
    <form @submit.prevent="onSubmit">
      <div class="form-content">
        <SectionTitle value="Fassadendämmung" />
        <InputGroup :row="true">
          <InputGroup>
            <label for="facade-material">Material</label>
            <select id="facade-material" v-model="state.facadeInsulatingMaterial" @change="resetInsulatedSides">
              <option disabled>Bitte wählen</option>
              <option v-for="option in INSULATING_MATERIAL_OPTIONS" :value="option.value" :key="option.value">
                {{ option.name }}
              </option>
            </select>
          </InputGroup>
          <InputGroup>
            <label for="facade-thickness">Dicke Dämmstoff (cm)</label>
            <input class="number" id="facade-thickness" type="number" v-model="state.facadeInsulatingMaterialThickness"
              :disabled="state.facadeInsulatingMaterial === null" />
          </InputGroup>
        </InputGroup>
        <SectionTitle value="Baustruktur" />
        <InputGroup :row="true">
          <InputGroup>
            <label for="facade-wall">Material</label>
            <select id="facade-wall" v-model="state.buildingStructure">
              <option disabled>Bitte wählen</option>
              <option v-for="option in BUILDING_MATERIAL_OPTIONS" :value="option.value" :key="option.value">
                {{ option.name }}
              </option>
            </select>
          </InputGroup>
          <InputGroup>
            <label for="facade-wall-thickness">Dicke Fassade (cm)</label>
            <InputWrapper>
              <input class="number" id="facade-wall-thickness" type="number"
                v-model="state.buildingStructureThickness" />
              <MessageBox msg="Geben Sie die Gesamtdicke der Außenwand ein." type="basic" />
            </InputWrapper>
          </InputGroup>
        </InputGroup>
        <SectionTitle value="Seitendämmung" />
        <MessageBox msg="Geben Sie bitte an, welche Seiten gedämmt sind." type="basic" />
        <InputGroup :row="true">
          <InputGroup>
            <label for="facade-north">Nord</label>
            <CheckboxWrapper value="gedämmt">
              <input id="facade-north" type="checkbox" v-model="state.facadeNorth" />
            </CheckboxWrapper>
          </InputGroup>
          <InputGroup>
            <label for="facade-west">West</label>
            <CheckboxWrapper value="gedämmt">
              <input id="facade-west" type="checkbox" v-model="state.facadeWest" />
            </CheckboxWrapper>
          </InputGroup>
          <InputGroup>
            <label for="facade-south">Süd</label>
            <CheckboxWrapper value="gedämmt">
              <input id="facade-south" type="checkbox" v-model="state.facadeSouth" />
            </CheckboxWrapper>
          </InputGroup>
          <InputGroup>
            <label for="facade-east">Ost</label>
            <CheckboxWrapper value="gedämmt">
              <input id="facade-east" type="checkbox" v-model="state.facadeEast" />
            </CheckboxWrapper>
          </InputGroup>
        </InputGroup>
        <InputGroup>
          <label for="facade-comment">Zusätzliche Kommentare</label>
          <MessageBox msg="Tragen Sie weitere Informationen zu den eingebauten Dämmstoffen ein." type="basic" />
          <textarea id="facade-comment" :rows="5" v-model="state.facadeRefurbishmentComment" />
        </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>