<script setup lang="ts">
import { Activity, AlertTriangle, ArrowDownUp, Clock3, Database, HardDrive, KeyRound, ListChecks, Mail, RefreshCw, Save, ShieldCheck, UserRound } from "lucide-vue-next";

defineProps<{ ctx: any }>();

const tabs = [
  { id: "database", label: "数据库", icon: Database },
  { id: "migration", label: "迁移状态", icon: HardDrive },
  { id: "sync", label: "旧项目同步", icon: RefreshCw },
  { id: "security", label: "安全与邮件", icon: ShieldCheck },
  { id: "health", label: "健康快照", icon: Activity },
  { id: "audit", label: "审计日志", icon: ListChecks },
];
</script>

<template>
  <section class="page-stack">
    <nav class="tabs" aria-label="系统运维标签">
      <button v-for="tab in tabs" :key="tab.id" type="button" :class="{ active: ctx.systemTab === tab.id }" @click="ctx.setSystemTab(tab.id)">
        <component :is="tab.icon" :size="15" />
        {{ tab.label }}
      </button>
    </nav>

    <section v-if="ctx.systemTab === 'database'" class="split">
      <section class="panel page-stack">
        <div class="section-head">
          <h2>数据库运行状态</h2>
          <span :class="['badge', ctx.statusTone(ctx.database?.activeProvider)]">{{ ctx.database?.activeProvider || "-" }}</span>
        </div>
        <div class="kv-grid">
          <span>配置类型</span><strong>{{ ctx.database?.configProvider || "-" }}</strong>
          <span>SQLite</span><strong>{{ ctx.database?.sqliteReady ? "ready" : "missing" }}</strong>
          <span>MySQL</span><strong>{{ ctx.database?.remoteReady ? "ready" : "offline" }}</strong>
          <span>Failover</span><strong>{{ ctx.database?.failoverActive ? "active" : "standby" }}</strong>
          <span>最后同步</span><strong>{{ ctx.database?.lastSyncAt || "-" }}</strong>
          <span>最近错误</span><strong>{{ ctx.database?.lastSyncError || ctx.database?.lastError || "-" }}</strong>
        </div>

        <div class="sync-summary">
          <div><span><ArrowDownUp :size="15" />最近方向</span><strong>{{ ctx.databaseSyncDirectionLabel(ctx.databaseLastSync?.direction) }}</strong></div>
          <div><span><ListChecks :size="15" />最近状态</span><strong>{{ ctx.databaseSyncStatusLabel(ctx.databaseLastSync?.status) }}</strong></div>
          <div><span><Clock3 :size="15" />影响记录</span><strong>{{ ctx.databaseSyncTableCount(ctx.databaseLastSync) }}</strong></div>
        </div>
        <div v-if="ctx.databaseLastSync?.warnings?.length" class="ops-note">
          <AlertTriangle :size="16" />
          <span>{{ ctx.databaseLastSync.warnings.join("；") }}</span>
        </div>
      </section>

      <aside class="panel editor-panel">
        <div class="section-head">
          <h2>连接与同步</h2>
          <div class="button-row compact-row">
            <span v-if="ctx.databaseFormEditing" class="badge warn">编辑中，自动刷新不会覆盖表单</span>
            <button v-if="ctx.databaseFormEditing" class="btn ghost compact" type="button" @click="ctx.reloadDatabaseConfig">重新读取配置</button>
            <button v-if="ctx.databaseConfigCollapsed" class="btn ghost compact" type="button" @click="ctx.editDatabaseConfig">修改配置</button>
          </div>
        </div>
        <div v-if="ctx.databaseConfigCollapsed" class="kv-grid">
          <span>当前配置</span><strong>{{ ctx.databaseConfigSummary() }}</strong>
          <span>密码状态</span><strong>{{ ctx.databaseConfig?.hasPassword ? "已保存，前端不回显" : "未保存" }}</strong>
        </div>

        <div v-else class="form-stack" @input="ctx.markDatabaseFormEditing" @change="ctx.markDatabaseFormEditing">
          <label>Provider
            <select v-model="ctx.databaseForm.provider">
              <option value="sqlite">SQLite</option>
              <option value="mysql">MySQL</option>
            </select>
          </label>
          <label v-if="ctx.databaseForm.provider === 'sqlite'">SQLite 路径
            <input v-model="ctx.databaseForm.sqlitePath" placeholder="留空使用当前配置" />
          </label>
          <div v-else class="form-grid">
            <label>主机<input v-model="ctx.databaseForm.mysqlHost" placeholder="127.0.0.1" /></label>
            <label>端口<input v-model.number="ctx.databaseForm.mysqlPort" type="number" min="1" placeholder="3306" /></label>
            <label>数据库名<input v-model="ctx.databaseForm.mysqlDatabase" placeholder="ymhut_unified" /></label>
            <label>数据库用户<input v-model="ctx.databaseForm.mysqlUser" autocomplete="username" /></label>
            <label class="wide">数据库密码
              <input v-model="ctx.databaseForm.mysqlPassword" type="password" autocomplete="new-password" :placeholder="ctx.databaseConfig?.hasPassword ? '留空沿用已保存密码' : '请输入数据库密码'" />
            </label>
          </div>
        </div>

        <div class="button-row">
          <button class="btn ghost" @click="ctx.testDatabase">测试连接</button>
          <button class="btn primary" @click="ctx.saveDatabase"><Save :size="16" />测试并保存</button>
          <button class="btn ghost" @click="ctx.syncDatabase('import')">SQLite -> MySQL</button>
          <button class="btn ghost" @click="ctx.syncDatabase('sync')">MySQL -> SQLite</button>
        </div>
      </aside>
    </section>

    <section v-else-if="ctx.systemTab === 'migration'" class="split">
      <section class="panel page-stack">
        <div class="section-head"><h2>数据库优先迁移</h2><button class="btn ghost" @click="ctx.loadMigrationStatus"><RefreshCw :size="16" />刷新</button></div>
        <div class="kv-grid">
          <span>策略</span><strong>{{ ctx.migrationStatus?.strategy || "-" }}</strong>
          <span>SQLite 文件</span><strong>{{ ctx.migrationStatus?.sqlitePath || "-" }}</strong>
          <span>活动数据库</span><strong>{{ ctx.migrationStatus?.activeProvider || "-" }}</strong>
          <span>最后同步</span><strong>{{ ctx.migrationStatus?.lastSyncAt || "-" }}</strong>
          <span>同步错误</span><strong>{{ ctx.migrationStatus?.lastSyncError || "-" }}</strong>
        </div>
        <div class="ops-note">
          <AlertTriangle :size="16" />
          <span>数据库保存站点结构化状态；发布包、下载文件和反馈附件仍属于文件资产，迁移时需要连同数据库一起备份。</span>
        </div>
      </section>

      <aside class="panel page-stack">
        <h2>数据库覆盖范围</h2>
        <ul class="plain-list">
          <li v-for="item in ctx.migrationStatus?.databaseCovers || []" :key="item">{{ item }}</li>
        </ul>
        <h2>文件资产目录</h2>
        <div v-for="asset in ctx.migrationStatus?.fileAssets || []" :key="asset.name" class="asset-row">
          <strong>{{ asset.name }}</strong>
          <span>{{ asset.description }}</span>
          <code>{{ asset.path }}</code>
        </div>
      </aside>
    </section>

    <section v-else-if="ctx.systemTab === 'sync'" class="panel page-stack">
      <div class="section-head">
        <div>
          <h2>旧项目同步</h2>
          <p class="muted">预览只检查旧目录和影响范围；执行前会备份当前兼容输出，再复制旧项目数据并导入记录。</p>
        </div>
        <button class="btn ghost" @click="ctx.previewLegacySync"><RefreshCw :size="16" />刷新预览</button>
      </div>
      <div class="sync-summary">
        <div><span>当前模式</span><strong>{{ ctx.legacySyncMode === "run" || ctx.legacySync?.dryRun === false ? "执行结果" : "Dry-run 预览" }}</strong></div>
        <div><span>状态</span><strong>{{ ctx.legacySync?.ok === false ? "存在错误" : "可继续" }}</strong></div>
        <div><span>完成时间</span><strong>{{ ctx.legacySync?.finishedAt || "-" }}</strong></div>
      </div>
      <div class="kv-grid">
        <span>复制文件</span><strong>{{ ctx.legacySync?.stats?.copiedFiles || 0 }}</strong>
        <span>复制目录</span><strong>{{ ctx.legacySync?.stats?.copiedDirectories || 0 }}</strong>
        <span>导入记录</span><strong>{{ ctx.legacySync?.stats?.importedRows || 0 }}</strong>
        <span>缺失路径</span><strong>{{ ctx.legacySync?.stats?.missingPaths || 0 }}</strong>
      </div>
      <pre class="json-preview tall">{{ ctx.pretty(ctx.legacySync) }}</pre>
      <div class="button-row"><button class="btn primary" @click="ctx.runLegacySync">执行旧项目同步</button></div>
    </section>

    <section v-else-if="ctx.systemTab === 'security'" class="split">
      <section class="panel editor-panel">
        <h2>修改后台密码</h2>
        <label>当前密码<input v-model="ctx.passwordForm.currentPassword" type="password" autocomplete="current-password" /></label>
        <label>新密码<input v-model="ctx.passwordForm.newPassword" type="password" autocomplete="new-password" /></label>
        <button class="btn primary" @click="ctx.changePassword"><KeyRound :size="16" />保存密码</button>
      </section>

      <section class="panel editor-panel">
        <div class="section-head">
          <h2>站点品牌</h2>
          <span class="badge neutral">{{ ctx.branding.developerName || "YMhut" }}</span>
        </div>
        <div class="brand-preview">
          <img :src="ctx.branding.siteIconUrl" alt="站点图标" />
          <img :src="ctx.branding.developerAvatarUrl" alt="开发者头像" />
          <strong>{{ ctx.branding.developerName }}</strong>
        </div>
        <label>站点图标 URL<input v-model="ctx.branding.siteIconUrl" /></label>
        <label>开发者头像 URL<input v-model="ctx.branding.developerAvatarUrl" /></label>
        <label>开发者名称<input v-model="ctx.branding.developerName" /></label>
        <label>反馈邮箱<input v-model="ctx.branding.feedbackEmail" /></label>
        <button class="btn primary" @click="ctx.saveBranding"><UserRound :size="16" />保存品牌</button>
      </section>

      <section class="panel editor-panel">
        <div class="section-head">
          <h2>反馈邮件通知</h2>
          <div class="button-row compact-row">
            <span v-if="ctx.mailConfigEditing" class="badge warn">编辑中，自动刷新不会覆盖表单</span>
            <button v-if="ctx.mailConfigEditing" class="btn ghost compact" type="button" @click="ctx.reloadMailConfig">重新读取配置</button>
            <span :class="['badge', ctx.mailConfig.configured ? 'good' : 'warn']">{{ ctx.mailConfig.configured ? "已配置" : "未完成" }}</span>
          </div>
        </div>
        <div class="form-grid" @input="ctx.markMailConfigEditing" @change="ctx.markMailConfigEditing">
          <label>SMTP 主机<input v-model="ctx.mailConfig.host" placeholder="smtp.example.com" /></label>
          <label>端口<input v-model.number="ctx.mailConfig.port" type="number" min="1" /></label>
          <label>加密方式
            <select v-model="ctx.mailConfig.secure">
              <option value="ssl">SSL/TLS</option>
              <option value="starttls">STARTTLS</option>
              <option value="none">不加密</option>
            </select>
          </label>
          <label>账号<input v-model="ctx.mailConfig.username" autocomplete="username" /></label>
          <label>密码<input v-model="ctx.mailConfig.password" type="password" autocomplete="new-password" :placeholder="ctx.mailConfig.hasPassword ? '留空沿用已保存密码' : '请输入 SMTP 密码'" /></label>
          <label>超时秒数<input v-model.number="ctx.mailConfig.timeoutSeconds" type="number" min="3" /></label>
          <label>发件地址<input v-model="ctx.mailConfig.fromAddress" /></label>
          <label>发件名称<input v-model="ctx.mailConfig.fromName" /></label>
          <label class="wide">开发者收件地址<input v-model="ctx.mailConfig.developerAddress" :placeholder="ctx.branding.feedbackEmail" /></label>
        </div>
        <div class="button-row">
          <button class="btn primary" @click="ctx.saveMailConfig"><Mail :size="16" />保存邮件配置</button>
          <button class="btn ghost" @click="ctx.testMail">发送测试邮件</button>
        </div>
      </section>
    </section>

    <section v-else-if="ctx.systemTab === 'health'" class="panel page-stack">
      <div class="section-head"><h2>健康快照</h2><span class="badge neutral">只读</span></div>
      <pre class="json-preview tall">{{ ctx.pretty(ctx.healthSnapshot) }}</pre>
    </section>

    <section v-else class="panel page-stack">
      <div class="section-head">
        <h2>审计日志</h2>
        <button class="btn ghost" @click="ctx.loadAudit">刷新</button>
      </div>
      <div class="toolbar">
        <input v-model="ctx.auditPage.q" placeholder="搜索操作、目标、信息或 IP" @keyup.enter="ctx.loadAudit" />
        <input v-model="ctx.auditPage.type" placeholder="类型，例如 source.deleted" @keyup.enter="ctx.loadAudit" />
        <input v-model="ctx.auditPage.target" placeholder="目标" @keyup.enter="ctx.loadAudit" />
        <button class="btn ghost" @click="ctx.auditPage.page = 1; ctx.loadAudit()">筛选</button>
      </div>
      <table>
        <thead><tr><th>类型</th><th>目标</th><th>信息</th><th>IP</th><th>时间</th></tr></thead>
        <tbody>
          <tr v-for="item in ctx.auditPage.items" :key="item.id" class="clickable" @click="ctx.selectAuditLog(item)">
            <td><span class="badge neutral">{{ ctx.auditTypeLabel(item.type) }}</span></td>
            <td>{{ item.target }}</td>
            <td>{{ ctx.auditMessage(item) }}</td>
            <td>{{ item.ip || "-" }}</td>
            <td>{{ item.createdAt }}</td>
          </tr>
          <tr v-if="ctx.auditPage.items.length === 0"><td colspan="5">暂无审计日志。</td></tr>
        </tbody>
      </table>
      <div class="pager">
        <button class="btn ghost compact" :disabled="ctx.auditPage.page <= 1" @click="ctx.setAuditPage(ctx.auditPage.page - 1)">上一页</button>
        <span>第 {{ ctx.auditPage.page }} 页 / 共 {{ Math.max(1, Math.ceil(ctx.auditPage.total / ctx.auditPage.perPage)) }} 页，{{ ctx.auditPage.total }} 条</span>
        <button class="btn ghost compact" :disabled="ctx.auditPage.page >= Math.ceil(ctx.auditPage.total / ctx.auditPage.perPage)" @click="ctx.setAuditPage(ctx.auditPage.page + 1)">下一页</button>
      </div>

      <Teleport to="body">
        <div v-if="ctx.auditPage.selected" class="modal-backdrop" @click.self="ctx.auditPage.selected = null">
          <section class="modal-panel">
            <div class="section-head">
              <h2>审计详情</h2>
              <button class="btn ghost compact" @click="ctx.auditPage.selected = null">关闭</button>
            </div>
            <pre class="json-preview tall">{{ ctx.pretty(ctx.auditPage.selected) }}</pre>
          </section>
        </div>
      </Teleport>
    </section>
  </section>
</template>
