<template>
  <nav class="bg-neutral-700">
    <div class="mx-auto px-4" :class="[showNavbarBreadcrumb? 'min-h-12': 'h-12']">
      <div class="flex justify-between items-center flex-wrap" v-show="showNavbarBreadcrumb">
        <div class="flex flex-1 items-center">
          <!-- 回 Files 頁 -->
          <router-link to class="mr-4" v-if="navViewName !== 'FILES'">
            <span @click="$router.back(-1)" class="material-symbols-outlined text-neutral-10 leading-loose">
              arrow_back
            </span>
          </router-link>
          <h2 class="mr-14 py-3 text-2xl font-black text-neutral-10">{{ navViewName }}</h2>
          <ul class="flex justify-center items-center space-x-4 text-xl font-semibold text-neutral-300 cursor-pointer">
            <li @click="switchNavItem($event)" v-for="(item, index) in navViewData[navViewName]" :key="index">{{ item }}</li>
          </ul>
        </div>
        <!-- Files Page: Search and Upload -->
        <div class="flex justify-end items-center" v-if="navViewName === 'FILES'">
          <form role="search">
            <label for="searchFiles" class="mr-4 relative">
              <input type="search" id="searchFiles" placeholder="Search" class="px-5 py-2 w-72 rounded-full text-sm align-middle duration-300 border border-neutral-500 hover:border-neutral-300 focus:outline-none focus:ring focus:border-neutral-300">
              <span class="absolute top-2 bottom-1.5 right-0.5 flex justify-center items-center gap-2">
                <IconSetting class="w-6 h-6 cursor-pointer"></IconSetting>
                <span class="w-px h-6 block after:border after:border-neutral-300 after:content-['']"></span>
                <button class="pr-2">
                  <IconSearch class="w-6 h-6"></IconSearch>
                </button>
              </span>
            </label>
          </form>
          <label class="btn btn-sm btn-neutral cursor-pointer">
            <input id="uploadFiles" class="hidden" type="file">
            upload
          </label>
        </div>
        <!-- Other Page: Save and Download -->
        <!-- Save 有 data 跳重新命名，沒有 data 跳要不要儲存，沒有動都不跳 -->
        <div v-else class="space-x-4">
          <button class="btn btn-sm btn-neutral" @click="showAlert">Save</button>
          <button class="btn btn-sm btn-neutral">Download</button>
        </div>
      </div>
    </div>
  </nav>
</template>

<script>
import filesStore from '@/stores/files.js';
import IconSearch from '@/components/icons/IconSearch.vue';
import IconSetting from '@/components/icons/IconSetting.vue';
import AllMapDataStore from '@/stores/allMapData.js';

export default {
  data() {
    return {
      showNavbarBreadcrumb: false,
      navViewData:
      {
        FILES: ['ALL', 'DISCOVER', 'COMPARE', 'DESIGN'],
        DISCOVER: ['MAP', 'CONFORMANCE', 'PERFORMANCE', 'DATA']
      },
      navViewName: 'FILES',
      sweetVal: '',
    };
  },
  watch: {
    '$route':'getNavViewName',
  },
  setup() {
    const store = filesStore();
    const allMapDataStore = AllMapDataStore();

    return { store, allMapDataStore}
  },
  components: {
    IconSearch,
    IconSetting,
  },
  mounted() {
    this.showNavbarBreadcrumb = this.$route.matched[0].name !== ('AuthContainer')? true : false;
    this.getNavViewName();
  },
  methods: {
    switchNavItem(event) {
      this.store.filesTag = event.target.innerText;
    },
    getNavViewName() {
      this.navViewName = this.$route.name.toUpperCase();
    },
    async showAlert() {
      const customClass = {
        htmlContainer: '!w-[564px]',
        title: '!text-xl !font-semibold !mb-2',
        htmlContainer: '!text-sm !font-normal !h-full !mb-4 !leading-5',
        inputLabel: '!text-sm !font-normal',
        input: '!h-8 !text-sm !font-normal !shadow-inner !shadow-black !border-neutral-200',
        validationMessage: '!bg-neutral-10 !text-danger',
        confirmButton: '!inline-block !rounded-full !text-sm !font-medium !text-center !align-middle !transition-colors !duration-300 !px-5 !py-2 !w-[100px] !h-[40px]',
        cancelButton: '!inline-block !rounded-full !text-sm !font-medium !text-center !align-middle !transition-colors !duration-300 !px-5 !py-2 !w-[100px] !h-[40px] ',
      };

      // 先判斷有沒有 filter Id，有就儲存 return，沒有就往下走

      // 沒有 filter Id, 沒有暫存 tempFilterId Id 就不能存檔
      if(!this.allMapDataStore.tempFilterId) return this.$toast.error('Unable to overwrite original file.');

     // 沒有 filter Id, 有暫存 tempFilterId Id 可以另存新檔
      const { value, isConfirmed } = await this.$swal({
        title: 'SAVE NEW FILTER',
        input: 'text',
        inputPlaceholder: 'Enter Filter Name.',
        inputValue: this.sweetVal,
        inputValidator: (value) => {
          if (!value) return 'You need to write something!';
          this.sweetVal = value;
        },
        icon: 'info',
        iconHtml: '<span class="material-symbols-outlined text-[58px]">cloud_upload</span>',
        iconColor: '#0099FF',
        reverseButtons:true,
        confirmButtonColor: '#0099FF',
        showCancelButton: true,
        cancelButtonColor: '#94a3b8',
        customClass: customClass,
      });
      // 存檔成功
      if(isConfirmed){
        // 打API
        let logId = this.$route.params.logId;
        const api = `/api/filters?log_id=${logId}`;
        let createFilterObj = {
          name: value,
          rules: this.allMapDataStore.postRuleData
        };

        try {
          const response = await this.axios.post(api, createFilterObj)
          let createFilterId = response.data.id;

        }catch(error) {
          console.dir(error);
        }
      }
      if (value) {
        await this.$swal({
          title: 'SAVE COMPLETE',
          html: `<span class="text-primary">${value}</span> has been saved in Lucia.`,
          showConfirmButton: false,
          icon: 'success',
          iconColor: '#0099FF',
          customClass: customClass
        })
      };
      // 有 aplly all 的話，是否存檔? 是:另存新檔或存檔 不是:離開
      const result = await this.$swal({
        title: 'ARE YOU SURE TO LEAVE MAP?',
        html: 'Filter settings have not been saved.</br>Click “Save as” to save filtered results, “OK” to leave map.',
        icon: 'warning',
        iconColor: '#FF3366',
        reverseButtons:true,
        confirmButtonText: 'Save as',
        confirmButtonColor: '#FF3366',
        showCancelButton: true,
        cancelButtonText: 'OK',
        cancelButtonColor: '#94a3b8',
        customClass: customClass
      })
      if(result.isConfirmed){
        // 有 createFilterId 直接存檔
        // 跳存檔成功 model
        console.log('存檔');
      }else if(result.dismiss === 'cancel'){
        console.log('離開 discover');
      }else if(result.dismiss === 'backdrop'){
        console.log('停留在原本的頁面');
      };
      // 最後清空
      this.sweetVal = '';
    }
  },
}
</script>

<style scoped>
#searchFiles::-webkit-search-cancel-button{
  appearance: none;
}
</style>
