<script setup>
import { ref, onMounted, watch } from 'vue'
import { useTheme } from 'vuetify'

const theme = useTheme()

const _mis_acis_theme = ref({
  themeMode: 'light',
  primaryColor: '#2196F3',
  cardSkin: 'bordered',
})

// 控制抽屉显示
const drawer = ref(false)

// 主题颜色选项
const primaryColors = [
  { name: 'Blue', value: '#2196F3' },
  { name: 'Purple', value: '#9155FD' },
  { name: 'Teal', value: '#16B1FF' },
  { name: 'Orange', value: '#FF9F43' },
  { name: 'Red', value: '#FF4C51' },
]

// 用户选择的主题模式（可以是 'light', 'dark', 'system'）
const themeMode = ref(_mis_acis_theme.value.themeMode)

// 检测系统主题
const getSystemTheme = () => {
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return 'dark'
  }

  return 'light'
}

// 应用主题
const applyTheme = mode => {
  if (mode === 'system') {
    // 系统模式：根据系统偏好设置主题
    const systemTheme = getSystemTheme()
    theme.change(systemTheme)
  } else {
    // 直接应用选择的主题
    theme.change(mode)
  }
}

// 监听主题模式变化
watch(themeMode, newMode => {
  _mis_acis_theme.value.themeMode = newMode
  localStorage.setItem('_mis_acis_theme', JSON.stringify(_mis_acis_theme.value))

  applyTheme(newMode)

  // 触发自定义事件通知主题变化
  window.dispatchEvent(new CustomEvent('themeChanged', { detail: _mis_acis_theme.value }))

  // 同步到 iframe
  setTimeout(syncThemeToIframes, 50)
})

// 当前主色调
const currentPrimaryColor = ref(_mis_acis_theme.value.primaryColor)

// 当前卡片样式 - 从 localStorage 读取
const cardSkin = ref(_mis_acis_theme.value.cardSkin)

// 切换主题颜色
const changePrimaryColor = color => {
  currentPrimaryColor.value = color
  _mis_acis_theme.value.primaryColor = color
  localStorage.setItem('_mis_acis_theme', JSON.stringify(_mis_acis_theme.value))

  // 更新主题颜色
  theme.themes.value.light.colors.primary = color
  theme.themes.value.dark.colors.primary = color

  // 触发自定义事件
  window.dispatchEvent(new CustomEvent('themeChanged', { detail: _mis_acis_theme.value }))

  // 同步到 iframe
  setTimeout(syncThemeToIframes, 50)
}

// 同步主题到 iframe
const syncThemeToIframes = () => {
  document.querySelectorAll('iframe').forEach(iframe => {
    try {
      const iframeDoc = iframe.contentDocument
      if (!iframeDoc?.documentElement) return

      // 同步主题模式
      iframeDoc.documentElement.setAttribute('data-theme', theme.global.name.value)

      // 同步卡片样式
      if (iframeDoc.body) {
        iframeDoc.body.className = iframeDoc.body.className.replace(/card-skin-\w+/g, '')
        iframeDoc.body.classList.add(`card-skin-${_mis_acis_theme.value.cardSkin}`)
      }

      // 同步 CSS 变量
      const parentStyle = getComputedStyle(document.documentElement)
      const vars = ['--v-theme-primary', '--v-theme-surface', '--v-theme-background']
      vars.forEach(v => {
        const val = parentStyle.getPropertyValue(v)
        if (val) iframeDoc.documentElement.style.setProperty(v, val)
      })

      // 触发 iframe 内事件
      iframe.contentWindow?.dispatchEvent(new CustomEvent('parentThemeChanged', {
        detail: _mis_acis_theme.value
      }))
    } catch (e) {
      // 跨域 iframe 会失败，忽略
    }
  })
}

// 切换卡片样式
const changeCardSkin = skin => {
  cardSkin.value = skin
  _mis_acis_theme.value.cardSkin = skin
  localStorage.setItem('_mis_acis_theme', JSON.stringify(_mis_acis_theme.value))

  // 触发自定义事件通知卡片样式变化
  window.dispatchEvent(new CustomEvent('cardSkinChange', { detail: skin }))

  // 更新全局 CSS 类名到 body 标签
  if (skin === 'bordered') {
    document.body.classList.add('card-skin-bordered')
    document.body.classList.remove('card-skin-default')
  } else {
    document.body.classList.add('card-skin-default')
    document.body.classList.remove('card-skin-bordered')
  }

  // 同步到 iframe
  setTimeout(syncThemeToIframes, 50)
}

// 打开抽屉
const openDrawer = () => {
  drawer.value = true
}

// 初始化时应用保存的主题颜色
onMounted(() => {
  // 从 localStorage 加载配置
  const savedConfig = localStorage.getItem('_mis_acis_theme')
  if (savedConfig) {
    try {
      const config = JSON.parse(savedConfig)
      Object.assign(_mis_acis_theme.value, config)

      // 更新各个 ref
      themeMode.value = config.themeMode || 'light'
      currentPrimaryColor.value = config.primaryColor || '#2196F3'
      cardSkin.value = config.cardSkin || 'default'
    } catch (e) {
      console.error('Failed to parse theme config:', e)
    }
  }

  // 应用主题颜色
  if (currentPrimaryColor.value) {
    changePrimaryColor(currentPrimaryColor.value)
  }

  // 应用主题模式
  if (themeMode.value) {
    applyTheme(themeMode.value)
  }

  // 初始化卡片样式
  if (cardSkin.value) {
    changeCardSkin(cardSkin.value)
  } else {
    changeCardSkin('bordered')
  }

  // 监听系统主题变化
  if (window.matchMedia) {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

    const handleThemeChange = e => {
      // 只在系统模式下响应系统主题变化
      if (themeMode.value === 'system') {
        theme.global.name = e.matches ? 'dark' : 'light'
      }
    }

    // 添加监听器
    mediaQuery.addEventListener('change', handleThemeChange)
  }

  // 监听新增的 iframe 并自动同步主题
  const observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
      mutation.addedNodes.forEach(node => {
        if (node.tagName === 'IFRAME') {
          node.addEventListener('load', () => setTimeout(syncThemeToIframes, 100))
        }
      })
    })
  })
  observer.observe(document.body, { childList: true, subtree: true })

  // 初始同步现有 iframe
  setTimeout(syncThemeToIframes, 500)
})

// 暴露方法供父组件调用
defineExpose({
  openDrawer,
})
</script>

<template>
  <!-- 侧边抽屉 -->
  <v-navigation-drawer v-model="drawer" temporary location="end" width="400" class="theme-customizer-drawer">
    <!-- 头部 -->
    <div class="customizer-header px-6 py-3 d-flex align-center justify-space-between">
      <div>
        <h2 class="text-h5 font-weight-bold mb-1">
          主题定制器
        </h2>
        <p class="text-body-2 text-medium-emphasis mb-0">
          实时定制和预览
        </p>
      </div>
      <v-btn icon variant="text" @click="drawer = false">
        <v-icon icon="mdi-close" />
      </v-btn>
    </div>

    <v-divider />

    <!-- 内容区域 -->
    <div class="customizer-content pa-6">
      <!-- 主题模式 -->
      <div class="mb-6">
        <v-label class="text-body-2 font-weight-medium mb-3 ps-1">
          颜色
        </v-label>
        <div class="d-flex mb-6">
          <v-btn class="ma-1" v-for="color in primaryColors" :key="color.value" icon size="small" :color="color.value"
            :variant="currentPrimaryColor === color.value ? 'elevated' : 'flat'"
            :class="{ 'color-selected': currentPrimaryColor === color.value }" @click="changePrimaryColor(color.value)">
            <v-icon v-if="currentPrimaryColor === color.value" icon="mdi-check" color="white" size="20" />
          </v-btn>
        </div>

        <v-label class="text-body-2 font-weight-medium mb-3 ps-1">
          主题
        </v-label>
        <div class="theme-options d-flex">
          <!-- 浅色主题 -->
          <div class="theme-option" :class="{ 'theme-option--active': themeMode === 'light' }"
            @click="themeMode = 'light'">
            <div class="theme-preview theme-preview--light">
              <v-icon icon="mdi-white-balance-sunny" size="32" />
            </div>
            <p class="text-body-2 text-center mt-2 mb-0">
              浅色
            </p>
          </div>

          <!-- 深色主题 -->
          <div class="theme-option" :class="{ 'theme-option--active': themeMode === 'dark' }"
            @click="themeMode = 'dark'">
            <div class="theme-preview theme-preview--dark">
              <v-icon icon="mdi-moon-waning-crescent" size="32" />
            </div>
            <p class="text-body-2 text-center mt-2 mb-0">
              深色
            </p>
          </div>

          <!-- 系统主题 -->
          <div class="theme-option" :class="{ 'theme-option--active': themeMode === 'system' }"
            @click="themeMode = 'system'">
            <div class="theme-preview theme-preview--system">
              <v-icon icon="mdi-desktop-classic" size="32" />
            </div>
            <p class="text-body-2 text-center mt-2 mb-0">
              跟随系统
            </p>
          </div>
        </div>
      </div>

      <!-- 卡片样式 -->
      <v-label class="text-body-2 font-weight-medium mb-3 ps-1">
        样式
      </v-label>
      <div class="mb-8">
        <div class="skin-options d-flex">
          <!-- Default 样式 -->
          <div class="skin-option" :class="{ 'skin-option--active': cardSkin === 'default' }"
            @click="changeCardSkin('default')">
            <div class="skin-preview skin-preview--default">
              <div class="skin-card-preview" />
            </div>
            <p class="text-body-2 text-center mt-2 mb-0">
              悬浮
            </p>
          </div>

          <!-- Bordered 样式 -->
          <div class="skin-option" :class="{ 'skin-option--active': cardSkin === 'bordered' }"
            @click="changeCardSkin('bordered')">
            <div class="skin-preview skin-preview--bordered">
              <div class="skin-card-preview skin-card-preview--bordered" />
            </div>
            <p class="text-body-2 text-center mt-2 mb-0">
              扁平
            </p>
          </div>
          <div class="skin-option" style="cursor:default;" />
        </div>
      </div>
    </div>
  </v-navigation-drawer>
</template>

<style lang="scss" scoped>
// 抽屉样式
.theme-customizer-drawer {
  :deep(.v-navigation-drawer__content) {
    display: flex;
    flex-direction: column;
  }
}

// 头部
.customizer-header {
  background: rgb(var(--v-theme-surface));
}

// 内容区域
.customizer-content {
  flex: 1;
  overflow-y: auto;
}

// 颜色按钮
.color-selected {
  border: 3px solid rgb(var(--v-theme-primary));
  box-shadow: 0 4px 12px rgba(var(--v-theme-primary), 0.4);
}

// 主题选项
.theme-options {
  .theme-option {
    flex: 1;
    cursor: pointer;
    transition: all 0.2s ease;
    padding: 4px;

    .theme-preview {
      width: 100%;
      height: 60px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2px solid rgba(var(--v-border-color), var(--v-border-opacity));
      transition: all 0.2s ease;
    }

    &--active .theme-preview {
      border-color: rgb(var(--v-theme-primary));
      box-shadow: 0 4px 12px rgba(var(--v-theme-primary), 0.3);
    }

    &:hover .theme-preview {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
  }
}

// 卡片样式选项
.skin-options {
  .skin-option {
    flex: 1;
    cursor: pointer;
    transition: all 0.2s ease;
    padding: 4px;

    .skin-preview {
      width: 100%;
      height: 80px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2px solid rgba(var(--v-border-color), var(--v-border-opacity));
      transition: all 0.2s ease;
      background: rgb(var(--v-theme-background));
      padding: 12px;

      &--default {
        .skin-card-preview {
          width: 100%;
          height: 100%;
          background: rgb(var(--v-theme-surface));
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }

      &--bordered {
        .skin-card-preview {
          width: 100%;
          height: 100%;
          background: rgb(var(--v-theme-surface));
          border-radius: 8px;
          border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
        }
      }
    }

    &--active .skin-preview {
      border-color: rgb(var(--v-theme-primary));
      box-shadow: 0 4px 12px rgba(var(--v-theme-primary), 0.3);
    }

    &:hover .skin-preview {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
  }
}

// 标签样式
.v-label {
  display: block;
  color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
}
</style>