<script setup>
import { useDialogPluginComponent } from "quasar";
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { fs } from "@hostlink/light";
const props = defineProps({
  selectedLocation: {
    type: String,
    required: true
  },
  initialFiles: {
    type: Array,
    default: () => []
  }
});
defineEmits([
  ...useDialogPluginComponent.emits
]);
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const $q = useQuasar();
const uploadFiles = ref([]);
const uploadProgress = ref({});
onMounted(() => {
  if (props.initialFiles && props.initialFiles.length > 0) {
    uploadFiles.value = props.initialFiles;
  }
});
const initializeUploadProgress = () => {
  uploadProgress.value = {};
  uploadFiles.value.forEach((file, index) => {
    uploadProgress.value[index] = {
      name: file.name,
      status: "pending",
      // pending, uploading, completed, failed
      error: null,
      progress: 0
    };
  });
};
const onUploadFiles = async () => {
  initializeUploadProgress();
  try {
    const uploadPromises = uploadFiles.value.map(
      (file, index) => (async () => {
        try {
          uploadProgress.value[index].status = "uploading";
          await fs.uploadFile(props.selectedLocation, file);
          uploadProgress.value[index].status = "completed";
          uploadProgress.value[index].progress = 100;
        } catch (error) {
          uploadProgress.value[index].status = "failed";
          uploadProgress.value[index].error = error?.message || String(error);
        }
      })()
    );
    await Promise.allSettled(uploadPromises);
    const failedUploads = Object.values(uploadProgress.value).filter((p) => p.status === "failed");
    if (failedUploads.length === 0) {
      setTimeout(() => {
        onDialogOK(uploadFiles.value);
        uploadProgress.value = {};
      }, 1e3);
    }
  } catch (e) {
    $q.dialog({
      title: "Error",
      message: e.message
    });
  }
};
const onCancel = () => {
  uploadProgress.value = {};
  uploadFiles.value = [];
  onDialogCancel();
};
</script>

<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card style="min-width: 400px;">
      <q-toolbar>
        <q-toolbar-title>{{ $t('Upload Files') }}</q-toolbar-title>
        <q-space></q-space>
        <q-btn 
          flat 
          round 
          dense 
          icon="sym_o_close" 
          v-close-popup 
          :disable="uploadFiles.length > 0 && Object.values(uploadProgress).some(p => p.status === 'uploading')"
        ></q-btn>
      </q-toolbar>
      <q-card-section>
        <!-- 顯示上傳進度 -->
        <div v-if="Object.keys(uploadProgress).length > 0" class="q-mb-md">
          <q-list bordered separator>
            <q-item v-for="(progress, index) in uploadProgress" :key="index">
              <q-item-section avatar>
                <q-icon 
                  v-if="progress.status === 'completed'"
                  name="sym_o_check_circle"
                  color="positive"
                  size="md"
                />
                <q-icon 
                  v-else-if="progress.status === 'failed'"
                  name="sym_o_error"
                  color="negative"
                  size="md"
                />
                <q-icon 
                  v-else-if="progress.status === 'uploading'"
                  name="sym_o_cloud_upload"
                  color="primary"
                  size="md"
                />
                <q-icon 
                  v-else
                  name="sym_o_schedule"
                  color="grey"
                  size="md"
                />
              </q-item-section>

              <q-item-section>
                <q-item-label>{{ progress.name }}</q-item-label>
                <q-item-label caption v-if="progress.status === 'uploading'">
                  上傳中...
                </q-item-label>
                <q-item-label caption v-else-if="progress.status === 'completed'" class="text-positive">
                  上傳完成
                </q-item-label>
                <q-item-label caption v-else-if="progress.status === 'failed'" class="text-negative">
                  {{ progress.error }}
                </q-item-label>
                <q-item-label caption v-else>
                  等待中...
                </q-item-label>
                
                <q-linear-progress 
                  v-if="progress.status === 'uploading' || progress.status === 'completed'"
                  :value="progress.progress / 100"
                  :color="progress.status === 'completed' ? 'positive' : 'primary'"
                  class="q-mt-xs"
                  stripe
                  rounded
                />
              </q-item-section>
            </q-item>
          </q-list>
        </div>

        <!-- 未上傳時顯示檔案選擇 -->
        <div v-else>
          <q-file v-model="uploadFiles" multiple name="file" :label="$t('Files')" color="primary" outlined />
        </div>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn 
          flat 
          :label="$t('Cancel')" 
          color="primary" 
          v-close-popup
          @click="onCancel"
          :disable="uploadFiles.length > 0 && Object.values(uploadProgress).some(p => p.status === 'uploading')"
        ></q-btn>
        <q-btn 
          flat 
          :label="$t('Upload')" 
          color="primary" 
          @click="onUploadFiles"
          :disable="uploadFiles.length === 0 || Object.keys(uploadProgress).length > 0"
        ></q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
