<script lang="ts" setup>
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import useStorage from '@/stores/storage'
import FolderForm from './FolderForm.vue'

const storageStore = useStorage()
const { file, currentInfo } = storeToRefs(storageStore)
const { createFolder, editFolder } = storageStore

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

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
}

defineExpose({
  triggerFolderCreate,
  triggerFolderEdit,
})

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

<template>
  <folder-form
    :mode="folderFormType"
    :tree="
      (['ตู้เอกสาร', 'ลิ้นชัก', 'แฟ้ม', 'แฟ้มย่อย'] as const)[currentInfo.dept]
    "
    v-if="currentInfo.dept < 4"
    v-model:open="folderFormState"
    v-model:name="folderFormData.name"
    @submit="submitFolderForm"
  />
</template>
