<script setup lang="ts">
import {computed, onMounted, ref} from "vue";
import type {Space} from "@/models/space";
// import {Vue3PullToRefresh} from "@amirafa/vue3-pull-to-refresh";
// import {spaceService} from "@/services/space-service";

// PrimeVue Toast
import {InputText} from "primevue";
import {Button} from "primevue";
import Toast from "primevue/toast"; // <— правильный импорт компонента
import {useToast} from "primevue/usetoast";
import {useSpaceStore} from "@/stores/spaceStore";
import {spaceService} from "@/services/space-service"; // нужен ToastService в main.ts
const toast = useToast();
const spaceStore = useSpaceStore();
const emits = defineEmits(["space-selected"])
const newSpaceName = ref<string>("")
const spaces = ref<Space[]>([]);
const spaceId = computed(() => {
 return  spaceStore.selectedSpaceId
})
const spaceName = computed(() => {
  return spaceStore.selectedSpaceName
})

const fetchData = async () => {
  try {
    spaces.value = await spaceStore.getSpaces();
  } catch (err: any) {
    console.error(err);
    toast.add({
      severity: "error",
      summary: "Ошибка загрузки данных",
      detail: err?.message ?? "Неизвестная ошибка",
      life: 3000,
      closable: true,
    });
  }
};

const createSpace = async () => {
  await spaceService.createSpace(newSpaceName.value)
  await fetchData()
}
const selectSpace =  (space: Space) => {
  spaceStore.setSpace(space.id, space.name);
  emits('space-selected', space);
}

// если нужно дергать из родителя:
// defineExpose({ fetchData });

onMounted(fetchData);
</script>

<template>
  <Toast/>
  <div class="flex space-list  w-full flex-col items-center justify-center gap-2 p-2">
    <!-- твой контент -->
    <div  v-if="spaces.length==0" class="card gap-4 !w-fit">
      <span>Enter your first space name</span>
      <InputText type="text" v-model="newSpaceName"></InputText>
      <Button @click="createSpace">Create</Button>
    </div>
    <div v-else class="!w-full">
    <span class="font-bold">Selected space: {{spaceName}}</span>
    <div v-for="space in spaces" :key="space.id" class="w-full h-full " @click="selectSpace(space)" >
      <div class="flex w-full flex-col justify-start  rounded-2xl p-2  bg-gray-50 gap-2" :class="spaceId === space.id ? '!bg-green-50' : 'bg-gray-50'">
        <span class=" font-medium ">{{ space.name }}</span>
        <div class="flex w-10 h-10 rounded-full bg-green-200 flex items-center justify-center ">
        <span class="font-bold ">{{
            space.owner.firstName.substring(0, 1).toUpperCase()
          }}</span>
        </div>
      </div>
    </div>
    </div>
  </div>
</template>

<style scoped>
</style>