<script setup lang="ts">

import {onMounted, ref} from "vue";
import {createSpaceRequest} from "@/services/spaceService";
import {Space} from "@/models/Space";

import FloatLabel from "primevue/floatlabel";
import Checkbox from "primevue/checkbox";
import InputText from "primevue/inputtext";
import Textarea from "primevue/textarea";
import Button from "primevue/button";
import DatePicker from "primevue/datepicker";
import {useToast} from "primevue/usetoast";
import LoadingView from "@/components/LoadingView.vue";

const emits = defineEmits(['space-created', 'close-modal', 'error-space-creation'])
const toast = useToast()


const spaceName = ref('')
const spaceDescription = ref('')
const createCategories = ref(true)
const loading = ref(false)

const cancel = () => {
  resetForm()
  emits("close-modal");
}

const createSpace = async () => {
  const space = new Space()
  space.name = spaceName.value
  space.description = spaceDescription.value
  space.createCategories = createCategories.value

  try {
    loading.value = true
    await createSpaceRequest(space)
        .then((res) => {
          resetForm()
          loading.value = false
          emits("space-created", res)
        }).catch((err) => {
          toast.add({
            severity: 'error',
            summary: 'Ошибка!',
            detail: err.response?.data?.message || 'Ошибка при создании пространства',
            life: 3000
          });
        })

  } catch (e) {
    console.error(e)
    emits('error-space-creation', e)
  }
}
const resetForm = () => {
  spaceName.value = ''
  spaceDescription.value = ''
}
</script>

<template>
  <LoadingView v-if="loading" halfscreen/>
  <div v-else class="flex flex-col gap-4 mt-1 h-80 items-center justify-between">
    <FloatLabel variant="on" class="w-full">
      <label for="name">Название</label>
      <InputText v-model="spaceName" id="name" class="w-full"/>
    </FloatLabel>
    <FloatLabel variant="on" class="w-full">
      <label for="name">Описание</label>
      <Textarea v-model="spaceDescription" id="name" class="w-full"/>
    </FloatLabel>
    <div class="flex flex-row items-center min-w-fit gap-4">
      <Checkbox v-model="createCategories" binary/>
      Создать стандартный набор категорий?
    </div>
    <div class="flex flex-row gap-2 justify-end items-center">
      <Button label="Создать" severity="success" icon="pi pi-save" @click="createSpace" class="!bg-blue-300 hover:!bg-blue-400 !border-blue-300"/>
      <Button label="Отмена" severity="secondary" icon="pi pi-times-circle" @click="cancel"/>
    </div>
  </div>
</template>

<style scoped>

</style>