<script setup>
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { Sunny, Moon, Monitor } from '@element-plus/icons-vue'

import { useSettingsStore } from '@/stores/settings'
import { useTheme, ThemeMode, themeOptions } from '@/composables/useTheme'
import TagManageDialog from './TagManageDialog.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:modelValue'])

const settingsStore = useSettingsStore()
const { searchShortcut } = storeToRefs(settingsStore)
const { themeMode, setTheme } = useTheme()

const shortcut = ref('Ctrl+K')
const selectedTheme = ref('light')
const isListening = ref(false)
const tagManageVisible = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

watch(
  () => props.modelValue,
  (open) => {
    if (open) {
      shortcut.value = searchShortcut.value ?? 'Ctrl+K'
      selectedTheme.value = themeMode.value || 'light'
    }
  }
)

const ignoreKeys = new Set(['Shift', 'Control', 'Alt', 'Meta', 'Tab'])

function formatKey(key) {
  if (key.length === 1) {
    return key.toUpperCase()
  }
  switch (key) {
    case ' ':
    case 'Spacebar':
    case 'Space':
      return 'Space'
    case 'ArrowUp':
      return 'ArrowUp'
    case 'ArrowDown':
      return 'ArrowDown'
    case 'ArrowLeft':
      return 'ArrowLeft'
    case 'ArrowRight':
      return 'ArrowRight'
    case 'Escape':
      return 'Esc'
    case 'Enter':
      return 'Enter'
    case 'Meta':
      return 'Cmd'
    default:
      return key.charAt(0).toUpperCase() + key.slice(1)
  }
}

function handleShortcutKeydown(event) {
  event.preventDefault()
  const keys = new Set()
  if (event.ctrlKey || event.metaKey) {
    keys.add(event.metaKey ? 'Cmd' : 'Ctrl')
  }
  if (event.shiftKey) {
    keys.add('Shift')
  }
  if (event.altKey) {
    keys.add('Alt')
  }
  const key = formatKey(event.key)
  if (!ignoreKeys.has(key) && key !== 'Cmd' && key !== 'Ctrl' && key !== 'Alt' && key !== 'Shift') {
    keys.add(key)
  }
  if (keys.size === 0) {
    return
  }
  shortcut.value = Array.from(keys).join('+')
}

async function handleThemeChange(value) {
  selectedTheme.value = value
  await setTheme(value)
}

async function saveSettings() {
  if (!shortcut.value) {
    ElMessage.error('快捷键不能为空')
    return
  }
  await settingsStore.updateSettings({
    searchShortcut: shortcut.value,
  })
  ElMessage.success('设置已保存')
  visible.value = false
}

function resetShortcut() {
  shortcut.value = 'Ctrl+K'
}

function getThemeIcon(value) {
  switch (value) {
    case ThemeMode.LIGHT:
      return Sunny
    case ThemeMode.DARK:
      return Moon
    case ThemeMode.SYSTEM:
      return Monitor
    default:
      return Sunny
  }
}
</script>

<template>
  <el-drawer v-model="visible" title="偏好设置" size="400px">
    <el-form label-position="top">
      <!-- 主题设置 -->
      <el-form-item label="外观主题">
        <el-radio-group 
          :model-value="selectedTheme" 
          @update:model-value="handleThemeChange"
          class="theme-radio-group"
        >
          <el-radio-button 
            v-for="option in themeOptions" 
            :key="option.value" 
            :value="option.value"
          >
            <component :is="getThemeIcon(option.value)" class="theme-icon" />
            {{ option.label }}
          </el-radio-button>
        </el-radio-group>
        <small class="hint">选择「跟随系统」将自动适配您的系统主题设置。</small>
      </el-form-item>

      <el-divider />

      <!-- 快捷键设置 -->
      <el-form-item label="全局搜索快捷键">
        <el-input
          v-model="shortcut"
          placeholder="点击后按下新的组合键..."
          readonly
          @focus="isListening = true"
          @blur="isListening = false"
          @keydown.stop.prevent="handleShortcutKeydown"
        />
        <small class="hint">聚焦输入框后，直接按下想要设置的按键组合即可。</small>
        <small v-if="isListening" class="listening">正在监听键盘输入...</small>
      </el-form-item>
      <el-form-item>
        <el-button text type="primary" @click="resetShortcut">恢复默认</el-button>
      </el-form-item>
      
      <el-divider />
      
      <!-- 标签管理 -->
      <el-form-item label="标签管理">
        <el-button type="primary" @click="tagManageVisible = true">管理标签顺序</el-button>
        <small class="hint">可以拖拽调整标签在书签列表中的显示顺序</small>
      </el-form-item>
    </el-form>
    <div class="drawer-actions">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="saveSettings">保存设置</el-button>
    </div>
    
    <TagManageDialog v-model="tagManageVisible" />
  </el-drawer>
</template>

<style scoped>
.hint {
  display: block;
  margin-top: 6px;
  color: var(--color-text-muted);
  font-size: 12px;
}

.listening {
  display: block;
  margin-top: 4px;
  color: var(--color-accent);
  font-size: 12px;
  font-weight: 600;
}

.drawer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.theme-radio-group {
  width: 100%;
}

.theme-radio-group :deep(.el-radio-button) {
  flex: 1;
}

.theme-radio-group :deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  width: 100%;
}

.theme-icon {
  width: 16px;
  height: 16px;
}
</style>
