<template>
  <q-page padding class="">
    <q-card flat bordered style="max-width: 1200px" class="q-mx-auto q-mb-lg">
      <q-card-section>
        <div class="text-h5">Ваша личная метавселенная</div>
      </q-card-section>
    </q-card>
    <q-card flat bordered style="max-width: 1200px" class="q-mx-auto">
      <q-card-section>
        <div class="text-h6">Проекты пользователя</div>
        <div class="text-subtitle2 text-grey">Управление вашими проектами</div>
      </q-card-section>
      <q-separator />
      <q-card-section class="flex">
        <q-space />

        <q-btn
          outline
          color="secondary"
          label="+Создать проект"
          @click="showCreateDialog = true"
        />
      </q-card-section>
      <q-card class="" flat v-if="projectsLength === 0">
        <q-card-section class="flex flex-center" v-if="beforekanvasoLoading">
          <q-spinner color="grey" size="3em" :thickness="5"></q-spinner>
        </q-card-section>
        <q-card-section v-else> No project </q-card-section>
      </q-card>
      <q-card-section>
        <q-list>
          <q-item
            clickable
            v-ripple
            v-for="project in projects"
            :key="project.node.uuid"
            :to="{ name: 'project', params: { uuid: project.node.uuid } }"
          >
            <q-item-section avatar>
              <q-icon size="xl" color="grey" name="space_dashboard" />
            </q-item-section>
            <q-item-section>
              <div class="ellipsis full-width">
                {{ project.node.nomo.enhavo }}
              </div>
              <div class="text-subtitle2 text-grey ellipsis full-width">
                {{ project.node.priskribo.enhavo }}
              </div>
            </q-item-section>

            <q-item-section side>
              <q-btn icon="more_horiz" flatmenu @click.prevent="">
                <q-menu>
                  <q-item
                    clickable
                    @click.prevent="onShowDeletDialog(project.node)"
                    updatedUuid="project.node.uuid;"
                    >Удалить</q-item
                  >
                  <q-item
                    clickable
                    @click.prevent="onShowUpdateDialog(project.node)"
                    >Настройки</q-item
                  >
                  <q-item
                    clickable
                    :to="{
                      name: 'Spaces',
                      params: { uuid: project.node.uuid },
                    }"
                    >EndlessCanvas</q-item
                  >
                </q-menu></q-btn
              >
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>
    </q-card>
  </q-page>
  <q-dialog v-model="showDeleteDialog">
    <q-card class="my-card">
      <q-card-section class="">
        <div class="text-h6">Удалить проект</div>
        <div class="text-subtitle2">Вы уверены, что хотите удалить проект?</div>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right">
        <q-btn
          outline
          label="Отмена"
          color="primary"
          @click="onCloseDeletDialog"
        />
        <q-btn
          outline
          label="Удалить"
          color="negative"
          @click="deleteProject"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
  <q-dialog v-model="showCreateDialog" max-width="5000">
    <q-card>
      <q-card-section>
        <div class="text-h6">Создание проекта</div>
        <q-input v-model="projectName" label="Название проекта" />
        <q-input v-model="projectDescription" label="Описание проекта" />
      </q-card-section>
      <q-card-actions align="right">
        <q-btn label="Отмена" @click="showCreateDialog = false" />
        <q-btn label="Создать" color="primary" @click="createProject" />
      </q-card-actions>
    </q-card>
  </q-dialog>
  <q-dialog v-model="showUpdateDialog" max-width="5000">
    <q-card>
      <q-card-section>
        <div class="text-h6">Изменение проекта</div>
        <q-input v-model="projectName" label="Название проекта" />
        <q-input v-model="projectDescription" label="Описание проекта" />
      </q-card-section>
      <q-card-actions align="right">
        <q-btn label="Отмена" @click="onCloseUpdateDialog" />
        <q-btn
          label="Изменить"
          color="primary"
          :disable="
            projectName === projectOldName &&
            projectDescription === projectOldDescription
          "
          @click="updateProject"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { useKanvasoStore } from '../stores/kanvaso';
import { useCurrentUserStore } from '../stores/current-user';
import { mapActions, mapState } from 'pinia';
import { debugLog } from '../utils';
export default defineComponent({
  data() {
    return {
      showCreateDialog: false,
      showUpdateDialog: false,
      showDeleteDialog: false,
      beforekanvasoLoading: true,
      projectName: '',
      projectDescription: '',
      projectOldName: '',
      projectOldDescription: '',
      updatedUuid: null,
    };
  },
  methods: {
    ...mapActions(useKanvasoStore, ['onGetKanvaso', 'onEditKanvaso']),
    getKanvaso() {
      this.onGetKanvaso()
        .then((res) => {
          debugLog('Get kanvaso: ', res);
          this.beforekanvasoLoading = false;
        })
        .catch((error) => {
          debugLog('Eror get Kanvaso: ', error);
        });
    },
    deleteProject() {
      this.showDeleteDialog = false;
      this.onEditKanvaso({
        uuid: this.updatedUuid,
        forigo: true,
        posedantoUzantoId: this.userId,
      })
        .then((res) => {
          debugLog('Delete Project: ', res);
          this.updatedUuid = null;

          this.getKanvaso();
        })
        .catch((error) => {
          debugLog(error);
        });
    },
    confirmDelete() {
      return true;
    },
    updateProject() {
      this.showUpdateDialog = false;
      this.onEditKanvaso({
        uuid: this.updatedUuid,
        nomo: this.projectName,
        priskribo: this.projectDescription,
        posedantoUzantoId: this.userId,
      })
        .then((res) => {
          debugLog('Update Project: ', res);
          this.updatedUuid = null;

          this.getKanvaso();
        })
        .catch((error) => {
          debugLog(error);
        });
      this.projectName = '';
      this.projectDescription = '';
      this.projectOldName = '';
      this.projectOldDescription = '';
    },
    createProject() {
      this.showCreateDialog = false;
      if (this.projectDescription && this.projectName) {
        this.onEditKanvaso({
          nomo: this.projectName,
          priskribo: this.projectDescription,
          posedantoUzantoId: this.userId,
        })
          .then((res) => {
            debugLog('Create Project: ', res);
            if (res.data?.redaktuKanvasojKanvaso?.kanvaso?.uuid) {
              this.$router.push({
                name: 'project',
                params: { uuid: res.data.redaktuKanvasojKanvaso.kanvaso.uuid },
              });
            }
            this.getKanvaso();
          })
          .catch((error) => {
            debugLog(error);
          });
        this.projectName = '';
        this.projectDescription = '';
      }
    },
    onShowDeletDialog(item) {
      this.updatedUuid = item.uuid;
      this.showDeleteDialog = true;
    },
    onShowUpdateDialog(item) {
      this.updatedUuid = item.uuid;
      this.projectName = item.nomo.enhavo;
      this.projectDescription = item.priskribo.enhavo;
      this.projectOldName = item.nomo.enhavo;
      this.projectOldDescription = item.priskribo.enhavo;
      this.showUpdateDialog = true;
    },
    onCloseDeletDialog() {
      this.showDeleteDialog = null;
      this.updatedUuid = null;
    },
    onCloseUpdateDialog() {
      this.showUpdateDialog = null;
      this.updatedUuid = null;
    },
  },
  computed: {
    ...mapState(useKanvasoStore, {
      projects: 'getKanvaso',
      projectsLength: 'getKanvasoLength',
    }),
    ...mapState(useCurrentUserStore, {
      userId: 'getUserId',
    }),
  },
  mounted() {
    this.getKanvaso();
  },
});
</script>
