<script setup lang="ts">
import axios from 'axios'
import { storeToRefs } from 'pinia'
import axiosClient from '@/services/HttpService'

import type { StorageFile } from '@/stores/storage'
import { useFileInfoStore } from '@/stores/file-info-data'

import FileIcon from '@/components/FileIcon.vue'

const { isFilePreview, fileInfo } = storeToRefs(useFileInfoStore())
const { getType, getFormatDate, getSize } = useFileInfoStore()
const filePath =
  (fileInfo.value?.pathname || '').split('/').slice(0, -1).join(' / ') + ' / '

async function downloadSubmit(path: string | undefined) {
  if (path) {
    let formatPath: string

    if (path.split('/').length - 1 === 3) {
      const [cabinet, drawer, folder, file] = path.split('/')
      formatPath = `cabinet/${cabinet}/drawer/${drawer}/folder/${folder}/file/${file}`
    } else {
      const [cabinet, drawer, folder, subfolder, file] = path.split('/')
      formatPath = `cabinet/${cabinet}/drawer/${drawer}/folder/${folder}/subfolder/${subfolder}/file/${file}`
    }

    const res = await axiosClient.get<StorageFile & { download: string }>(
      `${import.meta.env.VITE_API_ENDPOINT}${formatPath}`,
    )
    await axios
      .get(res.data.download, {
        method: 'GET',
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json',
          Accept: res.data.fileType,
        },
      })
      .then((r) => {
        const a = document.createElement('a')
        a.href = window.URL.createObjectURL(r.data)
        a.download = res.data.fileName
        a.click()
      })
  }
}
</script>

<template>
  <div class="bg-white rounded-borders shadow-5 relative q-pb-md">
    <div class="bg-white q-pa-md">
      <div class="row items-center">
        <span class="text-h6">
          <q-btn
            flat
            dense
            class="q-mr-sm q-px-sm"
            @click="() => (isFilePreview = false)"
            id="goBackInfo"
          >
            <q-icon
              class="pointer"
              name="arrow_back"
              size="1em"
              color="primary"
            />
          </q-btn>
          {{ fileInfo?.title }}</span
        >
        <span class="q-ml-lg text-grey">
          {{ filePath }}
        </span>
      </div>

      <div class="row q-mt-lg justify-center">
        <div class="column q-pa-sm">
          <div class="grid">
            <div
              :style="{
                position: 'relative',
                display: 'flex',
                gap: '0.5rem',
                flexDirection: 'column',
                alignItems: 'center',
                padding: '1rem',
                maxWidth: '100%',
              }"
              class="box"
            >
              <div class="q-px-md flex items-center justify-center">
                <file-icon
                  size="preview"
                  :fileName="fileInfo?.fileName ? fileInfo.fileName : 'unknown'"
                  :fileMimeType="
                    fileInfo?.fileType ? fileInfo.fileType : 'unknown'
                  "
                />
              </div>
              <div
                class="text-overflow-handle block q-px-md text-center"
                style="max-width: 100%"
              >
                {{ fileInfo?.title }}
              </div>
            </div>
            <div class="column q-py-sm">
              <q-btn
                color="primary"
                label="ดาวน์โหลด"
                icon="mdi-download"
                class="q-py-sm"
                @click="() => downloadSubmit(fileInfo?.pathname)"
                id="downloadSubmit"
              />
            </div>
          </div>
        </div>

        <div class="col-grow q-px-lg q-gutter-md q-pt-md">
          <div class="row">
            <div class="col-12 col-md-3">
              <span>ชื่อไฟล์</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{ fileInfo?.fileName }}</span>
            </div>
          </div>
          <q-separator />
          <div class="row">
            <div class="col-12 col-md-3">
              <span>ชื่อเรื่อง</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{ fileInfo?.title }}</span>
            </div>
          </div>
          <q-separator />
          <div class="row">
            <div class="col-12 col-md-3">
              <span>รายละเอียด</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{ fileInfo?.description }}</span>
            </div>
          </div>
          <q-separator />
          <div class="row">
            <div class="col-12 col-md-3">
              <span>กลุ่ม/หมวดหมู่</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{ fileInfo?.category.join(', ') }}</span>
            </div>
          </div>
          <q-separator />
          <div class="row">
            <div class="col-12 col-md-3">
              <span>คำสำคัญ</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{ fileInfo?.keyword.join(', ') }}</span>
            </div>
          </div>
          <q-separator />
          <div class="row">
            <div class="col-12 col-md-3">
              <span>ขนาดไฟล์</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{ getSize(fileInfo?.fileSize) }}</span>
            </div>
          </div>
          <q-separator />
          <div class="row">
            <div class="col-12 col-md-3">
              <span>ประเภทไฟล์</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{
                getType(fileInfo?.fileType, fileInfo?.fileName)
              }}</span>
            </div>
          </div>
          <q-separator />
          <div class="row">
            <div class="col-12 col-md-3">
              <span>วันที่อัปโหลด</span>
            </div>
            <div class="col-grow">
              <span class="text-grey">{{
                getFormatDate(fileInfo?.createdAt)
              }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.box {
  border: 2px solid $separator-color;
  border-radius: 8px;
}

.text-overflow-handle {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.grid {
  display: grid;
  width: 250px;
  grid-template-columns: repeat(1, minmax(0, 1fr));
  gap: 1rem;
}

.grid .box {
  position: relative;
}
</style>
