<template>
  <CustomModal
    :visible="isVisible"
    title="设置"
    size="large"
    @close="closeModal"
  >
    <div class="settings-content" :class="{ 'dark': themeStore.isDarkMode }">
      <!-- 设置导航 -->
      <div class="settings-nav">
        <div
          v-for="section in settingSections"
          :key="section.key"
          class="nav-item"
          :class="{ 'active': currentSection === section.key }"
          @click="currentSection = section.key"
        >
          <i :class="section.icon"></i>
          <span>{{ section.label }}</span>
        </div>
      </div>

      <!-- 设置内容 -->
      <div class="settings-main">
        <!-- 通用设置 -->
        <div v-if="currentSection === 'general'" class="setting-section">
          <h3 class="section-title">通用设置</h3>

          <div class="setting-group">
            <div class="setting-item">
              <div class="setting-info">
                <label>主题模式</label>
                <span class="setting-desc">选择应用的外观主题</span>
              </div>
              <div class="setting-control">
                <select v-model="settings.theme" @change="updateTheme">
                  <option value="light">亮色模式</option>
                  <option value="dark">暗色模式</option>
                  <option value="auto">跟随系统</option>
                </select>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <label>语言设置</label>
                <span class="setting-desc">选择应用显示语言</span>
              </div>
              <div class="setting-control">
                <select v-model="settings.language">
                  <option value="zh-CN">简体中文</option>
                  <option value="en-US">English</option>
                  <option value="ja-JP">日本語</option>
                </select>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <label>字体大小</label>
                <span class="setting-desc">调整聊天界面的字体大小</span>
              </div>
              <div class="setting-control">
                <input
                  type="range"
                  v-model="settings.fontSize"
                  min="12"
                  max="20"
                  step="1"
                  class="slider"
                />
                <span class="value-display">{{ settings.fontSize }}px</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 通知设置 -->
        <div v-if="currentSection === 'notifications'" class="setting-section">
          <h3 class="section-title">通知设置</h3>

          <div class="setting-group">
            <div class="setting-item">
              <div class="setting-info">
                <label>桌面通知</label>
                <span class="setting-desc">接收新消息的桌面通知</span>
              </div>
              <div class="setting-control">
                <label class="switch">
                  <input
                    type="checkbox"
                    v-model="settings.desktopNotifications"
                    @change="updateNotificationPermission"
                  />
                  <span class="slider-switch"></span>
                </label>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <label>声音提醒</label>
                <span class="setting-desc">新消息时播放提示音</span>
              </div>
              <div class="setting-control">
                <label class="switch">
                  <input type="checkbox" v-model="settings.soundNotifications"/>
                  <span class="slider-switch"></span>
                </label>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <label>通话通知</label>
                <span class="setting-desc">接收语音和视频通话邀请</span>
              </div>
              <div class="setting-control">
                <label class="switch">
                  <input type="checkbox" v-model="settings.callNotifications"/>
                  <span class="slider-switch"></span>
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 隐私设置 -->
        <div v-if="currentSection === 'privacy'" class="setting-section">
          <h3 class="section-title">隐私设置</h3>

          <div class="setting-group">
            <div class="setting-item">
              <div class="setting-info">
                <label>在线状态</label>
                <span class="setting-desc">是否向其他用户显示在线状态</span>
              </div>
              <div class="setting-control">
                <label class="switch">
                  <input type="checkbox" v-model="settings.showOnlineStatus"/>
                  <span class="slider-switch"></span>
                </label>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <label>已读回执</label>
                <span class="setting-desc">发送消息已读状态给对方</span>
              </div>
              <div class="setting-control">
                <label class="switch">
                  <input type="checkbox" v-model="settings.readReceipts"/>
                  <span class="slider-switch"></span>
                </label>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <label>自动下载</label>
                <span class="setting-desc">自动下载接收到的图片和文件</span>
              </div>
              <div class="setting-control">
                <label class="switch">
                  <input type="checkbox" v-model="settings.autoDownload"/>
                  <span class="slider-switch"></span>
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 关于 -->
        <div v-if="currentSection === 'about'" class="setting-section">
          <h3 class="section-title">关于应用</h3>

          <div class="about-content">
            <div class="app-info">
              <div class="app-icon">
                <i class="fas fa-comments"></i>
              </div>
              <div class="app-details">
                <h4>WebSocket 聊天系统</h4>
                <p>版本 1.0.0</p>
                <p>基于 Vue 3 + WebSocket 构建的现代化聊天应用</p>
              </div>
            </div>

            <div class="feature-list">
              <h5>主要功能</h5>
              <ul>
                <li>实时消息传输</li>
                <li>语音视频通话</li>
                <li>文件传输</li>
                <li>群聊功能</li>
                <li>暗色模式</li>
                <li>响应式设计</li>
              </ul>
            </div>

            <div class="action-buttons">
              <button class="btn secondary" @click="checkUpdate">
                <i class="fas fa-sync-alt"></i>
                检查更新
              </button>
              <button class="btn secondary" @click="clearCache">
                <i class="fas fa-trash"></i>
                清除缓存
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作 -->
    <template #footer>
      <div class="modal-footer">
        <button class="btn secondary" @click="resetSettings">
          重置设置
        </button>
        <div class="footer-actions">
          <button class="btn secondary" @click="closeModal">
            取消
          </button>
          <button class="btn primary" @click="saveSettings">
            保存设置
          </button>
        </div>
      </div>
    </template>
  </CustomModal>
</template>

<script setup>
import {ref, reactive, watch, onMounted} from 'vue'
import {useThemeStore} from '../stores/theme.ts'
import CustomModal from './CustomModal.vue'

const themeStore = useThemeStore()

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

const emit = defineEmits(['close'])

const isVisible = ref(false)
const currentSection = ref('general')

const settingSections = [
  {key: 'general', label: '通用', icon: 'fas fa-cog'},
  {key: 'notifications', label: '通知', icon: 'fas fa-bell'},
  {key: 'privacy', label: '隐私', icon: 'fas fa-shield-alt'},
  {key: 'about', label: '关于', icon: 'fas fa-info-circle'}
]

const settings = reactive({
  theme: 'light',
  language: 'zh-CN',
  fontSize: 14,
  desktopNotifications: true,
  soundNotifications: true,
  callNotifications: true,
  showOnlineStatus: true,
  readReceipts: true,
  autoDownload: true
})

const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('chat-settings')
    if (savedSettings) {
      Object.assign(settings, JSON.parse(savedSettings))
    }

    // 同步主题设置
    settings.theme = themeStore.isDarkMode ? 'dark' : 'light'
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

const saveSettings = () => {
  try {
    localStorage.setItem('chat-settings', JSON.stringify(settings))

    // 应用设置
    applySettings()

    // 显示保存成功提示
    showNotification('设置已保存', 'success')

    closeModal()
  } catch (error) {
    console.error('保存设置失败:', error)
    showNotification('保存设置失败', 'error')
  }
}

const applySettings = () => {
  // 应用主题
  // if (settings.theme === 'dark') {
  //   themeStore.toggleTheme(true)
  // } else if (settings.theme === 'light') {
  //   themeStore.setDarkMode(false)
  // } else {
  //   // 跟随系统
  //   const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
  //   themeStore.setDarkMode(prefersDark)
  // }
  //
  // // 应用字体大小
  // document.documentElement.style.setProperty('--base-font-size', `${settings.fontSize}px`)
}

const resetSettings = () => {
  if (confirm('确定要重置所有设置吗？')) {
    Object.assign(settings, {
      theme: 'light',
      language: 'zh-CN',
      fontSize: 14,
      desktopNotifications: true,
      soundNotifications: true,
      callNotifications: true,
      showOnlineStatus: true,
      readReceipts: true,
      autoDownload: true
    })

    showNotification('设置已重置', 'info')
  }
}

const updateTheme = () => {
  applySettings()
}

const updateNotificationPermission = async () => {
  if (settings.desktopNotifications && 'Notification' in window) {
    if (Notification.permission === 'default') {
      const permission = await Notification.requestPermission()
      if (permission !== 'granted') {
        settings.desktopNotifications = false
        showNotification('通知权限被拒绝', 'warning')
      }
    }
  }
}

const checkUpdate = () => {
  showNotification('当前已是最新版本', 'info')
}

const clearCache = () => {
  if (confirm('确定要清除所有缓存数据吗？')) {
    try {
      // 清除localStorage中的聊天数据
      const keysToRemove = []
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key && (key.startsWith('chat-') || key.startsWith('message-'))) {
          keysToRemove.push(key)
        }
      }

      keysToRemove.forEach(key => localStorage.removeItem(key))

      showNotification('缓存已清除', 'success')
    } catch (error) {
      console.error('清除缓存失败:', error)
      showNotification('清除缓存失败', 'error')
    }
  }
}

const showNotification = (message, type = 'info') => {
  // 这里应该调用全局通知组件
  console.log(`[${type.toUpperCase()}] ${message}`)
}

const closeModal = () => {
  isVisible.value = false
  emit('close')
}

watch(() => props.visible, (newValue) => {
  isVisible.value = newValue
  if (newValue) {
    loadSettings()
  }
})

onMounted(() => {
  loadSettings()
  applySettings()
})
</script>

<style scoped>
.settings-content {
  display: flex;
  height: 500px;
  overflow: hidden;
}

.settings-content.dark {
  color: #f7fafc;
}

.settings-nav {
  width: 200px;
  background: #f8fafc;
  border-right: 1px solid #e2e8f0;
  padding: 16px 0;
  overflow-y: auto;
}

.settings-content.dark .settings-nav {
  background: #374151;
  border-right-color: #4b5563;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #64748b;
  font-size: 14px;
}

.nav-item:hover {
  background: #e2e8f0;
  color: #374151;
}

.nav-item.active {
  background: #4361ee;
  color: white;
}

.settings-content.dark .nav-item {
  color: #9ca3af;
}

.settings-content.dark .nav-item:hover {
  background: #4b5563;
  color: #d1d5db;
}

.settings-main {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
  margin: 0 0 24px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
}

.settings-content.dark .section-title {
  color: #f7fafc;
  border-bottom-color: #374151;
}

.setting-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  transition: all 0.2s ease;
}

.setting-item:hover {
  border-color: #4361ee;
  box-shadow: 0 4px 12px rgba(67, 97, 238, 0.1);
}

.settings-content.dark .setting-item {
  background: #4b5563;
  border-color: #6b7280;
}

.settings-content.dark .setting-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.setting-info {
  flex: 1;
}

.setting-info label {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #1a202c;
  margin-bottom: 4px;
}

.settings-content.dark .setting-info label {
  color: #f7fafc;
}

.setting-desc {
  font-size: 14px;
  color: #64748b;
}

.settings-content.dark .setting-desc {
  color: #9ca3af;
}

.setting-control {
  display: flex;
  align-items: center;
  gap: 12px;
}

.setting-control select {
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: white;
  color: #1a202c;
  font-size: 14px;
  min-width: 120px;
}

.settings-content.dark .setting-control select {
  background: #374151;
  border-color: #4b5563;
  color: #f7fafc;
}

.slider {
  width: 120px;
  height: 6px;
  border-radius: 3px;
  background: #e2e8f0;
  outline: none;
  -webkit-appearance: none;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #4361ee;
  cursor: pointer;
}

.value-display {
  font-size: 14px;
  font-weight: 500;
  color: #4361ee;
  min-width: 40px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider-switch {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #e2e8f0;
  transition: 0.3s;
  border-radius: 24px;
}

.slider-switch:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: 0.3s;
  border-radius: 50%;
}

input:checked + .slider-switch {
  background-color: #4361ee;
}

input:checked + .slider-switch:before {
  transform: translateX(26px);
}

.about-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.app-info {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.settings-content.dark .app-info {
  background: #4b5563;
  border-color: #6b7280;
}

.app-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.app-details h4 {
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
  margin: 0 0 8px 0;
}

.settings-content.dark .app-details h4 {
  color: #f7fafc;
}

.app-details p {
  font-size: 14px;
  color: #64748b;
  margin: 0 0 4px 0;
}

.settings-content.dark .app-details p {
  color: #9ca3af;
}

.feature-list {
  padding: 20px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
}

.settings-content.dark .feature-list {
  background: #4b5563;
  border-color: #6b7280;
}

.feature-list h5 {
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
  margin: 0 0 12px 0;
}

.settings-content.dark .feature-list h5 {
  color: #f7fafc;
}

.feature-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.feature-list li {
  padding: 6px 0;
  color: #64748b;
  font-size: 14px;
  position: relative;
  padding-left: 20px;
}

.feature-list li:before {
  content: "✓";
  position: absolute;
  left: 0;
  color: #10b981;
  font-weight: bold;
}

.settings-content.dark .feature-list li {
  color: #9ca3af;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn.primary {
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
}

.btn.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(67, 97, 238, 0.3);
}

.btn.secondary {
  background: #f1f5f9;
  color: #64748b;
  border: 1px solid #e2e8f0;
}

.btn.secondary:hover {
  background: #e2e8f0;
  color: #475569;
}

.settings-content.dark .btn.secondary {
  background: #4b5563;
  color: #d1d5db;
  border-color: #6b7280;
}

.settings-content.dark .btn.secondary:hover {
  background: #6b7280;
  color: #f3f4f6;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-top: 1px solid #e2e8f0;
  background: #f8fafc;
}

.settings-content.dark .modal-footer {
  border-top-color: #374151;
  background: #374151;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-content {
    flex-direction: column;
    height: auto;
    max-height: 70vh;
  }

  .settings-nav {
    width: 100%;
    display: flex;
    overflow-x: auto;
    padding: 8px 0;
  }

  .nav-item {
    flex-shrink: 0;
    padding: 8px 16px;
    white-space: nowrap;
  }

  .settings-main {
    padding: 16px;
  }

  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .setting-control {
    width: 100%;
    justify-content: flex-end;
  }

  .modal-footer {
    flex-direction: column;
    gap: 12px;
  }

  .footer-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>
