<template>
  <div>
    <v-row>
      <v-col cols="12" sm="8">
        <v-card class="mx-auto" tile>
          <v-toolbar color="info" dark flat>
            <v-toolbar-title
              >Page {{ isNewPage ? 'creation' : 'editing' }}</v-toolbar-title
            >
            <v-spacer></v-spacer>
            <v-btn
              depressed
              color="white"
              light
              v-if="!isNewPage"
              nuxt
              :to="localePath(`/pages/${downloadedPage.slug}`)"
              target="_blank"
              text
            >
              <v-icon>mdi-open-in-new</v-icon>
            </v-btn>
            <v-btn
              depressed
              color="white"
              light
              to="/manager/pages/new"
              v-if="!isNewPage"
              text
            >
              <v-icon small>icon-add</v-icon>
            </v-btn>
          </v-toolbar>

          <v-card-text>
            <v-row>
              <v-col cols="12" sm="12" md="12">
                <v-text-field
                  v-model="localPage.title"
                  label="Title"
                  placeholder="Add here your title"
                ></v-text-field>
              </v-col>

              <v-col cols="12" sm="12" md="12">
                <v-text-field
                  v-model="localPage.subtitle"
                  label="Subtitle"
                  placeholder="Add here your subtitle"
                ></v-text-field>
              </v-col>

              <v-col cols="12" sm="12" md="12">
                <v-text-field
                  v-model="downloadedPage.slug"
                  label="Url"
                  disabled
                ></v-text-field>
              </v-col>
            </v-row>
          </v-card-text>

          <v-divider></v-divider>

          <v-card-actions class="my-6">
            <v-btn class="ma-2" color="info" tile depressed to="/manager/pages"
              >Back to pages</v-btn
            >

            <v-spacer></v-spacer>
            <v-btn
              class="ma-2"
              color="success"
              tile
              depressed
              @click="save"
              :disabled="!pageHasChanges"
              >Save</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-col>

      <v-col cols="12" sm="4">
        <ComponentsListToggler
          :componentsAttachedIds="componentsSortedIds"
          :model_id="this.downloadedPage.id"
          model="Page"
          @reload-resource="getPage(pageSlug)"
        />
      </v-col>
    </v-row>

    <draggable v-model="componentsSorted" @change="saveComponentsOrder">
      <transition-group>
        <v-card
          class="mx-auto my-4"
          v-for="(componentAttached, index) in componentsSorted"
          :key="componentAttached.name"
          tile
        >
          <v-toolbar color="indigo" dark flat>
            <v-toolbar-title>
              <v-avatar color="white" class="indigo--text mr-4" size="18">{{
                index + 1
              }}</v-avatar>
              {{ componentAttached.component_type.name }}
            </v-toolbar-title>

            <v-spacer></v-spacer>
            <v-btn icon>
              <v-icon small>icon-dragdrop</v-icon>
            </v-btn>
            <v-spacer></v-spacer>

            <v-btn icon>
              <v-icon>icon-edit</v-icon>
            </v-btn>
          </v-toolbar>

          <v-container fluid>
            <page-component :componentProp="componentAttached" />
          </v-container>
        </v-card>
      </transition-group>
    </draggable>
  </div>
</template>

<script>
// Get page slug name and make an api call to fetch components for that page

//  Based on https://github.com/vue-generators/vue-form-generator
//  DOCS https://vue-generators.gitbook.io/vue-generators/

import PageComponent from '@/components/PageComponent/PageComponent'
import ComponentsBar from '@/components/ComponentsBar/ComponentsBar'
import ComponentsListToggler from '@/components/ComponentsListToggler/ComponentsListToggler'
import Draggable from 'vuedraggable'

export default {
  components: {
    PageComponent,
    ComponentsBar,
    Draggable,
    ComponentsListToggler,
  },

  layout: `${process.env.CUSTOMER}Admin`,
  data: () => ({
    downloadedPage: {},
    localPage: {
      title: '',
      subtitle: '',
      url: '',
    },
    componentsSorted: [],

    dialog: false,
    valid: true,
    nameComponent: '',
    nameComponentRules: [
      (v) => !!v || 'Name is required',
      (v) => (v && v.length <= 20) || 'Name must be less than 20 characters',
    ],
    descriptionComponent: '',
    descriptionComponentRules: [
      (v) => !!v || 'Name is required',
      (v) =>
        (v && v.length <= 50) || 'Description must be less than 50 characters',
    ],
    lazy: false,
  }),

  watch: {
    downloadedPage: function () {
      this.componentsSorted = this.downloadedPage.components
    },
  },

  mounted() {
    if (!this.isValidSlug) this.$router.push('/')
    if (this.isNewPage) return
    if (this.isSlugNumber) this.getPage(this.pageSlug)
  },

  computed: {
    pageSlug() {
      return this.$route.params.page
    },
    isNewPage() {
      return this.pageSlug.toLowerCase() === 'new'
    },
    pageDownloaded() {
      return Object.keys(this.downloadedPage).length > 0
    },
    isSlugNumber() {
      return !isNaN(this.pageSlug.split(['-'], 1))
    },
    isValidSlug() {
      return this.isNewPage || this.isSlugNumber
    },
    pageHasChanges() {
      return (
        this.downloadedPage.title !== this.localPage.title ||
        this.downloadedPage.subtitle !== this.localPage.subtitle ||
        this.downloadedPage.slug !== this.localPage.slug
      )
    },
    componentsSortedIds() {
      return this.componentsSorted.length > 0
        ? this.componentsSorted.map(({ id }) => id)
        : []
    },
  },

  methods: {
    reset() {
      this.localPage.title = ''
      this.localPage.subtitle = ''
    },
    async save() {
      const data = {
        id: this.downloadedPage.id,
        title: this.localPage.title,
        subtitle: this.localPage.subtitle,
      }

      try {
        const response = await this.$axios.post('/pages', data)
        this.$router.push('/manager/pages')
      } catch (error) {
        this.$notifier.showMessage({
          content:
            `${
              this.$route.params.page.toLowerCase() === 'new'
                ? 'Creating'
                : 'Editing'
            } page: ` + error.message,
          color: 'error',
          icon: 'icon-message',
        })
      }
    },
    async getPage(pageUrl) {
      if (!this.isSlugNumber) return

      try {
        const response = await this.$axios.get(`/pages/${pageUrl}`)

        this.downloadedPage = response.data
        this.localPage.title = response.data.title
        this.localPage.subtitle = response.data.subtitle
        this.localPage.slug = response.data.slug
      } catch (error) {
        console.log('TCL: getPage -> error', error)
      }
    },

    async saveComponentsOrder() {
      const data = {
        components_ids: this.componentsSortedIds,
        model: 'Page',
        model_id: this.downloadedPage.id,
      }

      //todo add debounce
      try {
        await this.$axios.post('/components/sort', data)
      } catch (error) {
        console.log('TCL: saveComponentsOrder -> error', error)
      }
    },
  },
}
</script>
