<template>
  <pn-page-template v-bind="$attrs">
    <template #title>
      {{ $t('storage__title') }}
    </template>

    <q-list class="w100">
      <q-expansion-item
        v-for="item in storages.sort((a, b) => (+b.isActive - +a.isActive) ||((b.attach_date - a.attach_date)))"
        :key="item.id"
        group="storage"
        >
        <template #header>
          <q-item-section avatar>
            <q-img
              :src="'logos/' + getStorageInfo(item.type)?.logo"
              :class="item.isActive ? '' : 'greyscale'"  
            />
          </q-item-section>

          <q-item-section>
            <q-item-label lines="1">
              <q-icon
                v-if="!checkStorage(item)"
                dense
                name="mdi-exclamation-thick"
                color="negative"
                size="xs"
              />
              <q-badge :color="item.isActive ? 'positive' : 'grey'" class="q-mr-sm">
                {{ $t(item.isActive ? 'storage__storage_active' : 'storage__storage_passive') }}
              </q-badge>
              <span class="text-grey text-caption" v-if="item.attach_date">
                {{ $t('storage__storage_connect') + ' ' +
                  date.formatDate(item.attach_date * 1000, 'D MMM YY') }}
              </span>
            </q-item-label>
            <q-item-label
              lines="1"
              class="text-bold"
              :class="item.isActive ? '' : 'text-grey'"
              >
              {{ $t(getStorageInfo(item.type)?.name ?? '') }}
            </q-item-label>
            <q-item-label lines="1" caption>
              {{ item.type !== 1 ? item.email : $t('storage__storage_system') }}
            </q-item-label>
          </q-item-section>
        </template>
        <div
          class="column text-caption q-px-md"
          :class="item.isActive ? 'text-black' : 'text-grey'"
          >
          <div class="flex justify-between w100">
            <span>{{ $t('storage__max_file_size') }}</span>
            <span>{{ fileSize(getStorageInfo(item.type)?.maxFileSize ?? 0, $t) }}</span>
          </div>

          <div
            v-if="item.total_space"
            class="flex justify-between w100"
            >
            <span>{{ $t('storage__total_space') }}</span>
            <span>{{ fileSize(item.total_space, $t) }}</span>
          </div>

          <div
            v-if="item.used_space !== null && item.used_space !== undefined"
            class="flex justify-between w100"
            >
            <span>{{ $t('storage__app_files_size') }}</span>
            <span>{{ fileSize(item.used_space, $t) }}</span>
          </div>

          <div
            v-if="item.type === 1 || item.free_space"
            class="flex justify-between w100"
            :class="item.type !== 1 && checkStorage(item) ? 'text-ted' : ''"
            >
            <span>{{ $t('storage__available_space') }}</span>
            <span>
              {{ item.free_space ? fileSize(item.free_space, $t) : '&infin;' }}
            </span>
          </div>

          <div class="row w100 justify-end q-my-sm">
            <q-btn
              @click="onDelete(item.id)"
              flat no-caps
              color="negative"
              v-if="!item.isActive && (item.type !== 1)"
              >
              {{ $t('storage__storage_delete') }}
            </q-btn>
            
            <q-btn
              @click="onActivate(item.id)"
              flat no-caps
              color="primary"
              v-if="!item.isActive"
              >
              {{ $t('storage__storage_activate') }}
            </q-btn>
          </div>

        </div>
      </q-expansion-item>
    </q-list>
    
    <pn-onboard-btn
      v-if="storages.length <= 1"
      icon="mdi-folder-cog-outline"
      message1="storage__onboard_msg1"
      message2="storage__onboard_msg2"
      @click="addStorage"
    />
    
    <template #card-fab>
      <transition
        appear
        enter-active-class="animated zoomIn"
        >
        <pn-glass-btn
          type="fab"
          color="primary"
          >
          <q-btn
            fab unelevated
            class="shadow-t"
            icon="add"
            color="transparent"
            @click="addStorage"
          />
        </pn-glass-btn>
      </transition>
    </template>

    <pn-simple-scroll-dialog
      v-model="showSelectStorageDialog"
      title="storage__select_dialog_title"
      >
      <div class="q-py-none q-px-md q-ma-none">
        <div class="flex w100 text-center text-caption text-grey">
          {{ $t('storage__select_dialog_header_description') }}
        </div>
        <q-list class="q-pt-sm">
          <q-item
            v-for="item in availableStorages.filter(el => el.id !== 1)"
            :key="item.id"
            :type="item"
            clickable
            v-ripple
            v-close-popup
            class="w100"
            style="overflow: hidden"
            @click="attachStorage(item.url)"
            >
            <q-item-section avatar>
              <q-img :src="'logos/' + item.logo"/>
            </q-item-section>
            <q-item-section>
              <q-item-label>
                {{ $t(item.name) }}
              </q-item-label>
              <q-item-label caption v-if="item.description" class="text-grey">
                {{ $t(item.description) }}
              </q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </div>
    </pn-simple-scroll-dialog>

    <pn-small-dialog
      v-model="showDeleteStorageDialog"
      icon="mdi-folder-remove-outline"
      color="negative"
      title="storage__delete_dialog_title"
      message1="storage__delete_dialog_message"
      mainBtnLabel="storage__delete_dialog_ok"
      @clickMainBtn="onConfirmDeleteStorage"
      @close="deletedStorage = null"
    />
  </pn-page-template>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, inject } from 'vue'
  import { storeToRefs } from 'pinia'
  import pnSimpleScrollDialog from 'components/pnSimpleScrollDialog.vue'
  import pnGlassBtn from 'components/pnGlassBtn.vue'
  import { useAuthStore } from 'stores/auth'
  import { useStoragesStore } from 'stores/storages'
  import { date } from 'quasar'
  import { fileSize } from 'utils/files-functions'
  import type { FileStorage } from 'types/Storage'
  import type { WebApp } from '@twa-dev/types'

  const tg = inject('tg') as WebApp

  const showSelectStorageDialog = ref(false)
  const showDeleteStorageDialog = ref(false)
  const deletedStorage = ref<number | null>(null)

  const authStore = useAuthStore()
  const storageStore = useStoragesStore()
  const { ENV, customer } = storeToRefs(authStore)

  const storages = computed(() => 
    storageStore.storages.map((el: FileStorage) => ({
      ...el,
      isActive: customer.value?.storage_id === el.id,
    }))
  )

  const availableStorages = computed(() => [
    {
      id: 1,
      type: 1,
      logo: 'Telegram.png',
      name: 'storage__telegram',
      description: 'storage__telegram_description',
      description_list: 'storage__telegram_description2',
      maxFileSize: ENV.value?.TELEGRAM_MAX_FILE_SIZE,
      maxFileCount: ENV.value?.TELEGRAM_MAX_FILE_COUNT
    },
    {
      id: 2,
      type: 2,
      logo: 'YandexDisk.png',
      name: 'storage__yandex_disk',
      url: `https://oauth.yandex.ru/authorize?response_type=code&client_id=${ENV.value?.YANDEX_CLIENT_ID}&redirect_uri=${ENV.value?.YANDEX_REDIRECT_URI}&force_confirm=1`,
      description: 'storage__yandex_disk_description',
      description_list: 'storage__yandex_disk_description2',
      maxFileSize: ENV.value?.YANDEX_MAX_FILE_SIZE,
      maxFileCount: ENV.value?.YANDEX_MAX_FILE_COUNT
    },
    {
      id: 3,
      type: 3,
      logo: 'GoogleDrive.webp',
      name: 'storage__google_drive',
      url: `https://accounts.google.com/o/oauth2/v2/auth?client_id=${ENV.value?.GOOGLE_CLIENT_ID}&redirect_uri=${ENV.value?.GOOGLE_REDIRECT_URI}&response_type=code&scope=https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.email&access_type=offline&prompt=consent`,
      description: 'storage__google_drive_description',
      description_list: 'storage__google_drive_description2',
      maxFileSize: ENV.value?.GOOGLE_MAX_FILE_SIZE,
      maxFileCount: ENV.value?.GOOGLE_MAX_FILE_COUNT
    }
  ])

  const getStorageInfo = (type: number) => availableStorages.value.find(el => el.type === type) 
  const addStorage = () => showSelectStorageDialog.value = true

  async function onConfirmDeleteStorage () {
    if (deletedStorage.value) {
      await storageStore.remove(deletedStorage.value)
      deletedStorage.value = null
    }
  }

  function onDelete (id: number | null) {
    deletedStorage.value = id
    showDeleteStorageDialog.value = true
  }

  async function onActivate (id: number) {
    await storageStore.activate(id)
    await authStore.updateProfile()
  }

  function checkStorage (storage: FileStorage) {
    if (!storage.free_space || !storage.used_space) return true
    return storage.free_space * 0.2 > storage.used_space
  }

  onMounted(() => storageStore.getStorages())

  // const router = useRouter()

  function attachStorage (url: string | undefined) {
    if (!url) return
    sessionStorage.setItem('fromExternal', 'true')
    tg.BackButton.hide()
    window.location.href = url
  }

  onMounted(() => tg.BackButton.show())
</script>

<style scoped lang="scss">
  :deep(.q-expansion-item--expanded) {
    box-shadow: inset 0 0 0.5px 0.5px #e0e0e0;
  }

  .greyscale {
    filter: grayscale(100%);
  }
</style>
