<script setup>
import { q, m } from "#imports";
import { Loading, Notify } from "quasar";
import { ref, onMounted } from "vue";
const isUploading = ref(false);
const selectedFile = ref(null);
const fileInput = ref(null);
const databaseInfo = ref(null);
const fetchDatabaseInfo = async () => {
  try {
    const info = await q({
      system: {
        database: {
          type: true,
          sizeBytes: true,
          version: true
        }
      }
    });
    databaseInfo.value = info.system.database;
  } catch (e) {
    console.error("Failed to fetch database info:", e);
  }
};
const onFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    if (file.type === "application/sql" || file.name.endsWith(".sql")) {
      selectedFile.value = file;
    } else {
      Notify.create({
        type: "negative",
        message: "\u8ACB\u9078\u64C7 SQL \u6A94\u6848 (.sql)",
        position: "top"
      });
      event.target.value = "";
    }
  }
};
const clearFile = () => {
  selectedFile.value = null;
  if (fileInput.value) {
    fileInput.value.value = "";
  }
};
const onClickRestore = async () => {
  if (!selectedFile.value) {
    Notify.create({
      type: "negative",
      message: "\u8ACB\u5148\u9078\u64C7\u8981\u9084\u539F\u7684 SQL \u6A94\u6848",
      position: "top"
    });
    return;
  }
  isUploading.value = true;
  Loading.show({ message: "\u6B63\u5728\u9084\u539F\u8CC7\u6599\u5EAB\uFF0C\u8ACB\u7A0D\u5019..." });
  try {
    const result = await m("restoreDatabase", {
      file: selectedFile.value
    });
    Notify.create({
      type: "positive",
      message: "\u8CC7\u6599\u5EAB\u9084\u539F\u6210\u529F\uFF01",
      position: "top"
    });
    clearFile();
    await fetchDatabaseInfo();
  } catch (e) {
    console.error("Restore failed:", e);
    Notify.create({
      type: "negative",
      message: "\u9084\u539F\u5931\u6557\uFF0C\u8ACB\u6AA2\u67E5\u6A94\u6848\u683C\u5F0F\u6216\u7A0D\u5F8C\u518D\u8A66\u3002",
      position: "top"
    });
  } finally {
    Loading.hide();
    isUploading.value = false;
  }
};
const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};
onMounted(() => {
  fetchDatabaseInfo();
});
</script>

<template>
    <l-page title="資料庫還原">
        <div class="import-container">
            <!-- 頁面說明 -->
            <l-card class="info-card">
                <div class="card-header">
                    <h5 class="card-title">
                        <q-icon name="sym_o_info" class="text-primary" />
                        還原說明
                    </h5>
                </div>
                <div class="card-content">
                    <p class="description">
                        資料庫還原功能可以從 SQL 備份檔案恢復資料庫內容。
                        請確保上傳的 SQL 檔案來源可信且格式正確。
                    </p>
                </div>
            </l-card>

            <!-- 當前資料庫資訊 -->
            <l-card class="status-card">
                <div class="card-header">
                    <h5 class="card-title">
                        <q-icon name="sym_o_database" class="text-secondary" />
                        當前資料庫資訊
                    </h5>
                </div>
                <div class="card-content">
                    <div class="info-grid">
                        <div class="info-item" v-if="databaseInfo">
                            <q-icon name="sym_o_storage" class="info-icon" />
                            <div class="info-content">
                                <span class="info-label">資料庫類型</span>
                                <span class="info-value">{{ databaseInfo.type || '未知' }}</span>
                            </div>
                        </div>
                        <div class="info-item" v-if="databaseInfo">
                            <q-icon name="sym_o_storage" class="info-icon" />
                            <div class="info-content">
                                <span class="info-label">當前大小</span>
                                <span class="info-value">{{ databaseInfo.sizeBytes ? (databaseInfo.sizeBytes / 1024 /
                                    1024).toFixed(2) + ' MB' : '計算中...' }}</span>
                            </div>
                        </div>
                        <div class="info-item" v-if="databaseInfo && databaseInfo.version">
                            <q-icon name="sym_o_info" class="info-icon" />
                            <div class="info-content">
                                <span class="info-label">資料庫版本</span>
                                <span class="info-value">{{ databaseInfo.version }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </l-card>

            <!-- 安全警告 -->
            <l-alert type="negative" class="security-alert">
                <template #prefix>
                    <q-icon name="sym_o_warning" />
                </template>
                <strong>重要警告：</strong>還原資料庫將會完全覆蓋現有資料，此操作無法復原。建議在還原前先進行當前資料庫的備份。
            </l-alert>

            <!-- 檔案上傳區域 -->
            <l-card class="upload-card">
                <div class="card-header">
                    <h5 class="card-title">
                        <q-icon name="sym_o_upload" class="text-primary" />
                        選擇備份檔案
                    </h5>
                </div>
                <div class="card-content">
                    <div class="upload-area" :class="{ 'has-file': selectedFile }">
                        <input ref="fileInput" type="file" accept=".sql,application/sql" @change="onFileChange"
                            class="file-input" id="sql-file-input" />

                        <div v-if="!selectedFile" class="upload-placeholder">
                            <q-icon name="sym_o_cloud_upload" class="upload-icon" />
                            <p class="upload-text">點擊選擇 SQL 檔案</p>
                            <p class="upload-hint">支援 .sql 格式的檔案</p>
                            <label for="sql-file-input" class="upload-button">
                                <l-btn label="選擇檔案" icon="sym_o_folder_open" color="primary" />
                            </label>
                        </div>

                        <div v-else class="file-info">
                            <div class="file-details">
                                <q-icon name="sym_o_description" class="file-icon" />
                                <div class="file-content">
                                    <span class="file-name">{{ selectedFile.name }}</span>
                                    <span class="file-size">{{ formatFileSize(selectedFile.size) }}</span>
                                </div>
                            </div>
                            <l-btn icon="sym_o_close" color="negative" flat round @click="clearFile"
                                class="remove-btn" />
                        </div>
                    </div>
                </div>
            </l-card>

            <!-- 還原按鈕區域 -->
            <div class="restore-section">
                <l-btn :label="isUploading ? '正在還原中...' : '開始還原資料庫'" icon="sym_o_restore" color="primary" size="lg"
                    :loading="isUploading" :disabled="isUploading || !selectedFile" @click="onClickRestore"
                    class="restore-btn" />
                <p class="restore-hint">
                    請確認已備份當前資料庫，還原操作將無法復原
                </p>
            </div>
        </div>
    </l-page>
</template>

<style scoped>
.import-container{display:flex;flex-direction:column;gap:24px;margin:0 auto;max-width:800px;padding:20px}.info-card,.status-card,.upload-card{border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.1)}.card-header{padding:20px 24px 0}.card-title{align-items:center;color:#2c3e50;display:flex;font-weight:600;gap:8px;margin:0}.card-content{padding:16px 24px 24px}.description{color:#5a6c7d;line-height:1.6;margin:0}.info-grid{display:grid;gap:16px}.info-item{align-items:center;background:#f8f9fa;border-radius:8px;display:flex;gap:12px;padding:12px}.info-icon{color:#6c757d;font-size:24px}.info-content{display:flex;flex-direction:column;gap:4px}.info-label{color:#6c757d;font-size:14px;font-weight:500}.info-value{color:#2c3e50;font-size:16px;font-weight:600}.security-alert{border-radius:8px}.upload-area{background:#fafbfc;border:2px dashed #dee2e6;border-radius:12px;min-height:200px;position:relative;transition:all .3s ease}.upload-area:hover{background:#f8f9ff;border-color:#007bff}.upload-area.has-file{background:#f8fff9;border-color:#28a745}.file-input{cursor:pointer;height:100%;opacity:0;position:absolute;width:100%;z-index:1}.upload-placeholder{align-items:center;display:flex;flex-direction:column;height:200px;justify-content:center;text-align:center}.upload-icon{color:#007bff;font-size:64px;margin-bottom:16px}.upload-text{color:#2c3e50;font-size:18px;font-weight:600;margin:0 0 8px}.upload-hint{color:#6c757d;font-size:14px;margin:0 0 20px}.upload-button{cursor:pointer;position:relative;z-index:2}.file-info{height:200px;justify-content:space-between;padding:20px}.file-details,.file-info{align-items:center;display:flex}.file-details{gap:16px}.file-icon{color:#28a745;font-size:48px}.file-content{display:flex;flex-direction:column;gap:4px}.file-name{color:#2c3e50;font-size:16px;font-weight:600}.file-size{color:#6c757d;font-size:14px}.remove-btn{flex-shrink:0}.restore-section{background:linear-gradient(135deg,#fff3cd,#ffeeba);border:2px solid #ffc107;border-radius:16px;padding:32px 24px;text-align:center}.restore-btn{border-radius:8px;box-shadow:0 4px 12px rgba(255,193,7,.3);font-size:16px;font-weight:600;height:48px;margin-bottom:12px;min-width:240px;transition:all .3s ease}.restore-btn:hover:not(:disabled){box-shadow:0 6px 20px rgba(255,193,7,.4);transform:translateY(-2px)}.restore-btn:disabled{opacity:.6}.restore-hint{color:#856404;font-size:14px;font-weight:500;margin:0 auto;max-width:400px}@media (max-width:768px){.import-container{gap:20px;padding:16px}.card-content{padding:12px 20px 20px}.upload-area{min-height:160px}.file-info,.upload-placeholder{height:160px}.file-info{padding:16px}.restore-section{padding:24px 20px}.restore-btn{min-width:100%}}
</style>
