<script setup>
import { onMounted, ref } from 'vue'

import AppBar from '@/components/AppBar.vue'
import BuildingPicker from '@/components/BuildingPicker.vue'
import ContentLoading from '@/components/ContentLoading.vue'
import ModalContainer from '@/components/ModalContainer.vue'
import PageContainer from '@/components/PageContainer.vue'
import PageContent from '@/components/PageContent.vue'
import BuildingForm from '@/components/forms/BuildingForm.vue'
import { useApartmentStore } from '@/stores/apartments'
import { useBuildingStore } from '@/stores/buildings'
import { useUserStore } from '@/stores/users'

const isLoading = ref(true)
const showModal = ref(false)

const apartments = useApartmentStore()
const buildings = useBuildingStore()
const users = useUserStore()

function handleModal() {
  showModal.value = !showModal.value
}

onMounted(() => {
  Promise.all([
    apartments.fetchApartments(),
    buildings.fetchBuildings(),
    users.fetchUsers()
  ])
    .then(() => {
      isLoading.value = false
    })
})
</script>

<template>
  <PageContainer v-if="!isLoading">
    <AppBar>
      <BuildingPicker />
      <button v-if="buildings.firstBuilding?.setupCompleted" class="button secondary" type="button" @click="handleModal">
        <div class="button-content">
          <span>Neues Gebäude</span>
        </div>
        <div class="button-icon">
          <font-awesome-icon icon="fa-solid fa-plus" />
        </div>
      </button>
    </AppBar>
    <PageContent>
      <router-view></router-view>
    </PageContent>
  </PageContainer>
  <ContentLoading v-else />
  <ModalContainer v-if="showModal" label="Gebäude anlegen" @close-modal="handleModal">
    <BuildingForm @close-modal="handleModal" />
  </ModalContainer>
</template>