<script lang="ts" setup>
import { computed, ref } from 'vue'
import { storeToRefs } from 'pinia'
import type { QTableProps } from 'quasar'
import { useTreeDataStore, type TreeDataFolder } from '@/stores/tree-data'
import { useFileInfoStore } from '@/stores/file-info-data'
import FileIcon from '@/components/FileIcon.vue'
import DialogDelete from '@/components/DialogDelete.vue'
import FileForm from './FileForm.vue'
import FolderForm from './FolderForm.vue'

const { getFormatDate, getSize, getType, getFileInfo } = useFileInfoStore()
const { listDataFile, listDataFolder, currentDept, currentPath } = storeToRefs(
  useTreeDataStore()
)
const {
  createFolder,
  editFolder,
  getFolder,
  deleteFolder,
  uploadFile,
  updateFile,
  deleteFile,
  checkFile,
} = useTreeDataStore()

const DEPT_NAME = ['ตู้เอกสาร', 'ลิ้นชัก', 'แฟ้ม', 'แฟ้มย่อย'] as const

const props = defineProps<{
  mode: 'admin' | 'user'
}>()

const currentLevel = computed(() =>
  currentDept.value === 0
    ? 'ตู้จัดเก็บเอกสาร'
    : currentDept.value === 1
    ? 'ลิ้นชัก'
    : currentDept.value === 2
    ? 'แฟ้ม'
    : 'แฟ้มย่อย'
)

const currentIcon = computed(() =>
  currentDept.value === 0
    ? 'mdi-file-cabinet'
    : currentDept.value === 1
    ? 'inbox'
    : 'o_folder_open'
)

const folderFormState = ref<boolean>(false)
const folderFormPath = ref<string>('')
const folderFormData = ref<{
  name?: string
}>({})
const folderFormType = ref<'edit' | 'create'>('create')
const fileFormError = ref<{ fileExist?: boolean }>({})
const fileExistNotification = ref<boolean>(false)

const fileFormState = ref<boolean>(false)
const fileFormPath = ref<string>('')
const fileFormData = ref<{
  file?: File
  title?: string
  description?: string
  keyword?: string[]
  category?: string[]
}>({})
const fileFormType = ref<'edit' | 'create'>('create')

const dialogDeleteState = ref<boolean>(false)
const deleteFormPath = ref<string>('')
const deleteFormType = ref<'deleteFolder' | 'deleteFile'>()

function triggerFolderDelete(pathname: string) {
  deleteFormType.value = 'deleteFolder'
  deleteFormPath.value = pathname
  dialogDeleteState.value = !dialogDeleteState.value
}

function triggerFileDelete(pathname: string) {
  deleteFormType.value = 'deleteFile'
  deleteFormPath.value = pathname
  dialogDeleteState.value = !dialogDeleteState.value
}

function triggerFolderCreate() {
  folderFormType.value = 'create'
  folderFormData.value = {}
  folderFormState.value = !folderFormState.value
}

function triggerFolderEdit(name: string, pathname: string) {
  folderFormType.value = 'edit'
  folderFormPath.value = pathname
  folderFormData.value.name = name
  folderFormState.value = true
}

async function submitFolderForm(value: {
  mode: 'create' | 'edit'
  name: string
}) {
  if (value.mode === 'create') {
    await createFolder(value.name)
  } else {
    await editFolder(value.name, folderFormPath.value)
  }
}

function triggerFileCreate() {
  fileFormType.value = 'create'
  fileFormData.value = {}
  fileFormState.value = !fileFormState.value
}

function triggerFileEdit(
  value: {
    title: string
    description: string
    keyword: string[]
    category: string[]
  },
  pathname: string
) {
  fileFormState.value = true
  fileFormType.value = 'edit'
  fileFormPath.value = pathname
  fileFormData.value = {
    title: value.title,
    description: value.description,
    keyword: value.keyword,
    category: value.category,
  }
}

const currentParam = ref<Parameters<typeof submitFileForm>[0]>()

async function submitFileForm(
  value: {
    mode: 'create' | 'edit'
    file?: File
    title: string
    description: string
    keyword: string[]
    category: string[]
  },
  force = false
) {
  currentParam.value = value

  if (value.file && checkFile(value.file.name) && !force) {
    fileExistNotification.value = true
    return
  }

  if (value.mode === 'create' && value.file) {
    await uploadFile(currentPath.value, value.file, {
      title: value.title,
      description: value.description,
      keyword: value.keyword,
      category: value.category,
    })
  } else {
    await updateFile(
      fileFormPath.value,
      {
        title: value.title,
        description: value.description,
        keyword: value.keyword,
        category: value.category,
      },
      value.file
    )
  }
  fileFormData.value = {}
  fileFormState.value = false
  currentParam.value = undefined
}

const columnsFolder: QTableProps['columns'] = [
  {
    name: 'name',
    required: true,
    label: 'ชื่อ',
    align: 'left',
    field: (row) => row.name,
    format: (val) => `${val}`,
    sortable: true,
    style: 'width: 1000px',
  },
  {
    name: 'createdBy',
    align: 'center',
    label: 'สร้างโดย',
    field: 'createdBy',
    style: 'width: 20px',

    sortable: true,
  },
  {
    name: 'createdAt',
    align: 'center',
    label: 'วันที่สร้าง',
    field: 'createdAt',
    sortable: true,
    style: 'width: 20px',
  },
  {
    name: 'actions',
    align: 'center',
    label: '',
    field: '',
    style: 'width: 5px',
  },
]

const columnsFile: QTableProps['columns'] = [
  {
    name: 'name',
    required: true,
    label: 'ชื่อไฟล์',
    align: 'left',
    field: (row) => row.fileName,
    format: (val) => `${val}`,
    sortable: true,
    style: 'width: 200px',
  },
  {
    name: 'title',
    align: 'center',
    label: 'ชื่อเรื่อง',
    field: 'title',
    style: 'width: 200px',

    sortable: true,
  },
  {
    name: 'fileType',
    align: 'center',
    label: 'ประเภทของไฟล์',
    field: 'fileType',
    sortable: true,
    style: 'width: 200px',
  },
  {
    name: 'actions',
    align: 'center',
    label: '',
    field: '',
    style: 'width: 20px',
  },
]

const onRowClick = (evt: Event, row: TreeDataFolder, index: number) => {
  getFolder(row.pathname)
}
</script>

<template>
  <div class="q-mt-md">
    <div class="q-gutter-sm">
      <div
        class="flex flex-break d justify-between space-between"
        v-if="currentDept >= 1 && props.mode == 'admin' && currentDept != 4"

      >
        <div>
          <span class="text-h6">{{ currentLevel }}</span>
        </div>
        <div>
          <q-btn
            
            outline
            push
            class="q-px-md q-ml-md q-py-sm"
            :label="'สร้าง' + currentLevel"
            type="submit"
            color="primary"
            dense
            icon="add"
            @click="() => triggerFolderCreate()"
          />
        </div>
      </div>

      <q-table
        flat
        bordered
        :rows="listDataFolder"
        :columns="columnsFolder"
        row-key="name"
        hide-bottom
        :rows-per-page-options="[0]"
        @row-click="onRowClick"
        class="cursor"
        v-if=" currentDept != 4 "
      >
        <template v-slot:body-cell-name="nameRow">
          <q-td style="width: 50%">
            <q-icon :name="currentIcon" size="2em" color="primary" />
            {{ nameRow.row.name }}
          </q-td>
        </template>
        <template v-slot:body-cell-createdAt="createdAtRow">
          <q-td>
            <div class="justify-center">
              {{ getFormatDate(createdAtRow.row.createdAt) }}
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-actions="actionsRow">
          <q-td class="justify-center">
            <div>
              <q-icon class="q-ma-sm" name="info" size="2em" color="primary" />
              <q-tooltip
                anchor="center left"
                self="center right"
                :offset="[5, 1]"
              >
                {{ actionsRow.row.name }}
              </q-tooltip>
            </div>
            <div v-if="props.mode === 'admin'">
              <q-btn
                flat
                color="positive"
                dense
                icon="edit"
                @click.stop="
                  triggerFolderEdit(
                    actionsRow.row.name,
                    actionsRow.row.pathname
                  )
                "
              />
              <q-btn
                flat
                color="negative"
                dense
                icon="delete"
                @click.stop="triggerFolderDelete(actionsRow.row.pathname)"
              />
            </div>
          </q-td>
        </template>
      </q-table>
    </div>
  </div>

  <div class="q-mt-md" v-if="currentDept >= 3">
    <div class="q-gutter-sm">
      <div class="flex flex-break d justify-between space-between">
        <div>
          <span class="text-h6">เอกสาร</span>
        </div>
        <div>
          <q-btn
            v-if="props.mode == 'admin'"
            outline
            push
            class="q-px-md q-ml-md q-py-sm"
            label="สร้างเอกสาร"
            type="submit"
            color="primary"
            dense
            icon="add"
            @click="() => triggerFileCreate()"
          />
        </div>
      </div>
      <q-table
        flat
        bordered
        :rows="listDataFile"
        :columns="columnsFile"
        row-key="name"
        hide-bottom
        :rows-per-page-options="[0]"
        class="cursor"
      >
        <template v-slot:body-cell-name="nameRow">
          <q-td
            style="width: 50%"
            @click="
              () => {
                currentDept >= 3
                  ? getFileInfo(nameRow.row)
                  : getFolder(nameRow.row.pathname)
              }
            "
          >
            <file-icon size="list" :fileMimeType="nameRow.row.fileType" />
            {{ nameRow.row.fileName }}
          </q-td>
        </template>

        <template v-slot:body-cell-fileType="fileTypeRow">
          <q-td>
            <div class="justify-center">
              {{ getType(fileTypeRow.row.fileType) }}
            </div>
          </q-td>
        </template>

        <template v-slot:body-cell-actions="actionsRow">
          <q-td class="justify-center">
            <div>
              <q-icon class="q-ma-sm" name="info" size="2em" color="primary" />
              <q-tooltip
                anchor="center left"
                self="center right"
                :offset="[5, 1]"
              >
                {{ getSize(actionsRow.row.fileSize) }}
              </q-tooltip>
            </div>
            <div v-if="props.mode === 'admin'">
              <q-btn
                flat
                color="positive"
                dense
                icon="edit"
                @click="
                  () => triggerFileEdit(actionsRow.row, actionsRow.row.pathname)
                "
              />
              <q-btn
                flat
                color="negative"
                dense
                icon="delete"
                @click="() => triggerFileDelete(actionsRow.row.pathname)"
              />
            </div>
          </q-td>
        </template>
      </q-table>
    </div>
  </div>

  <file-form
    :mode="fileFormType"
    :error="fileFormError"
    v-model:open="fileFormState"
    v-model:title="fileFormData.title"
    v-model:description="fileFormData.description"
    v-model:keyword="fileFormData.keyword"
    v-model:category="fileFormData.category"
    @filechange="(name: string) => (fileFormError.fileExist = checkFile(name))"
    @submit="submitFileForm"
  />

  <folder-form
    :mode="folderFormType"
    :tree="DEPT_NAME[currentDept]"
    v-if="currentDept < 4"
    v-model:open="folderFormState"
    v-model:name="folderFormData.name"
    @submit="submitFolderForm"
  />

  <dialog-delete
    v-model:open="dialogDeleteState"
    @confirm="
      () =>
        deleteFormType &&
        (deleteFolder(deleteFormPath), deleteFile(deleteFormPath))
    "
  />
</template>

<style lang="scss" scoped>
.justify-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.cursor {
  cursor: pointer;
}
</style>
