<template>
  <v-card id="terminal-quick-commands" elevation="0" border rounded="lg" class="mb-4">
    <v-card-title class="d-flex align-center flex-wrap ga-2">
      <v-icon class="mr-1">mdi-flash</v-icon>
      终端快捷命令
      <v-spacer />
      <v-btn size="small" color="primary" variant="flat" prepend-icon="mdi-plus" @click="openCreate">
        添加命令
      </v-btn>
    </v-card-title>
    <v-divider />
    <v-card-text>
      <div class="text-body-2 text-medium-emphasis mb-4">
        自定义命令显示在终端栏最前（优先级最高）。终端页仅可点击执行；在此添加、编辑、删除与调整顺序。
      </div>

      <v-progress-linear v-if="loading" indeterminate color="primary" class="mb-3" />

      <div v-if="customCommands().length === 0 && !loading" class="text-medium-emphasis text-body-2 mb-4">
        暂无自定义命令，点击「添加命令」创建。
      </div>

      <v-list v-if="customCommands().length" density="compact" class="mb-4 pa-0">
        <v-list-item
          v-for="(cmd, index) in customCommands()"
          :key="cmd.id"
          border
          rounded="lg"
          class="mb-2"
        >
          <template #prepend>
            <span class="text-caption text-medium-emphasis mr-2" style="min-width: 1.5rem">{{ index + 1 }}</span>
          </template>
          <v-list-item-title>{{ cmd.name }}</v-list-item-title>
          <v-list-item-subtitle class="font-mono text-truncate">{{ cmd.cmd }}</v-list-item-subtitle>
          <template #append>
            <v-btn
              icon="mdi-arrow-up"
              size="x-small"
              variant="text"
              :disabled="index === 0 || savingOrder"
              @click="moveUp(index)"
            />
            <v-btn
              icon="mdi-arrow-down"
              size="x-small"
              variant="text"
              :disabled="index === customCommands().length - 1 || savingOrder"
              @click="moveDown(index)"
            />
            <v-btn icon="mdi-pencil" size="x-small" variant="text" @click="openEdit(cmd)" />
            <v-btn icon="mdi-delete" size="x-small" variant="text" color="error" @click="confirmRemove(cmd)" />
          </template>
        </v-list-item>
      </v-list>

      <div class="text-subtitle-2 mb-2">系统内置（不可编辑）</div>
      <div class="d-flex flex-wrap ga-2">
        <v-chip
          v-for="cmd in builtinCommands()"
          :key="cmd.id"
          size="small"
          variant="outlined"
          label
        >
          {{ cmd.name }}
        </v-chip>
      </div>
    </v-card-text>

    <v-dialog v-model="showEditor" max-width="520">
      <v-card border>
        <v-card-title>{{ editingId ? '编辑命令' : '添加快捷命令' }}</v-card-title>
        <v-card-text>
          <v-text-field v-model="formName" label="显示名称" variant="outlined" density="compact" class="mb-3" />
          <div class="text-body-2 text-medium-emphasis mb-2">命令内容（发送时自动追加回车）</div>
          <ShellHighlightField v-model="formCmd" multiline :rows="4" placeholder="systemctl status nginx" />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="showEditor = false">取消</v-btn>
          <v-btn color="primary" variant="flat" :loading="saving" @click="save">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="showDelete" max-width="400">
      <v-card border>
        <v-card-title>删除命令</v-card-title>
        <v-card-text>确定删除「{{ deletingName }}」？</v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="showDelete = false">取消</v-btn>
          <v-btn color="error" variant="flat" :loading="saving" @click="doDelete">删除</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import ShellHighlightField from '@/components/ShellHighlightField.vue'
import { useSnackbar } from '@/composables/useSnackbar'
import { useTerminalQuickCommands, type QuickCmdItem } from '@/composables/useTerminalQuickCommands'

const snackbar = useSnackbar()
const { commands, loading, load, create, update, remove, reorder, customCommands, builtinCommands } =
  useTerminalQuickCommands()

const showEditor = ref(false)
const editingId = ref<number | null>(null)
const formName = ref('')
const formCmd = ref('')
const saving = ref(false)
const savingOrder = ref(false)

const showDelete = ref(false)
const deletingId = ref<number | null>(null)
const deletingName = ref('')

function openCreate() {
  editingId.value = null
  formName.value = ''
  formCmd.value = ''
  showEditor.value = true
}

function openEdit(cmd: QuickCmdItem) {
  editingId.value = cmd.id
  formName.value = cmd.name
  formCmd.value = cmd.cmd.replace(/\r$/, '')
  showEditor.value = true
}

async function save() {
  if (!formName.value.trim() || !formCmd.value.trim()) {
    snackbar('名称和命令不能为空', 'warning')
    return
  }
  let cmdText = formCmd.value.trim()
  if (!cmdText.endsWith('\r')) cmdText += '\r'
  saving.value = true
  try {
    if (editingId.value) await update(editingId.value, formName.value, cmdText)
    else await create(formName.value, cmdText)
    showEditor.value = false
    snackbar('已保存')
  } catch (e: unknown) {
    snackbar(e instanceof Error ? e.message : '保存失败', 'error')
  } finally {
    saving.value = false
  }
}

function confirmRemove(cmd: QuickCmdItem) {
  deletingId.value = cmd.id
  deletingName.value = cmd.name
  showDelete.value = true
}

async function doDelete() {
  if (!deletingId.value) return
  saving.value = true
  try {
    await remove(deletingId.value)
    showDelete.value = false
    snackbar('已删除')
  } catch (e: unknown) {
    snackbar(e instanceof Error ? e.message : '删除失败', 'error')
  } finally {
    saving.value = false
  }
}

async function moveUp(index: number) {
  const list = customCommands()
  if (index <= 0) return
  const ids = list.map((c) => c.id)
  const prev = ids[index - 1]
  ids[index - 1] = ids[index]
  ids[index] = prev
  await applyOrder(ids)
}

async function moveDown(index: number) {
  const list = customCommands()
  if (index >= list.length - 1) return
  const ids = list.map((c) => c.id)
  const next = ids[index + 1]
  ids[index + 1] = ids[index]
  ids[index] = next
  await applyOrder(ids)
}

async function applyOrder(ids: number[]) {
  savingOrder.value = true
  try {
    await reorder(ids)
  } catch (e: unknown) {
    snackbar(e instanceof Error ? e.message : '排序失败', 'error')
  } finally {
    savingOrder.value = false
  }
}

onMounted(() => {
  load().catch((e) => snackbar(e.message, 'error'))
})
</script>
