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

const theme = useTheme()

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

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

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

// 检测系统主题
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 => {
  localStorage.setItem('themeMode', newMode)
  applyTheme(newMode)
})

// 当前主色调
const currentPrimaryColor = ref(localStorage.getItem('primaryColor') || '#9155FD')

// 当前布局 - 从 localStorage 读取（使用 ref 以便响应式更新）
const currentLayout = ref(localStorage.getItem('layout') || 'horizontal')

// 当前卡片样式 - 从 localStorage 读取
const cardSkin = ref(localStorage.getItem('cardSkin') || 'default')

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

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

// 切换布局
const changeLayout = layout => {
  localStorage.setItem('layout', layout)

  // 更新当前布局状态（用于 UI 显示）
  currentLayout.value = layout

  // 触发自定义事件通知布局变化
  window.dispatchEvent(new CustomEvent('layoutChange', { detail: layout }))
}

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

  // 触发自定义事件通知卡片样式变化
  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')
  }
}

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

// 初始化时应用保存的主题颜色
onMounted(() => {
  const savedColor = localStorage.getItem('primaryColor')
  if (savedColor) {
    changePrimaryColor(savedColor)
  }

  const savedMode = localStorage.getItem('themeMode')
  if (savedMode) {
    themeMode.value = savedMode
    applyTheme(savedMode)
  }

  // 初始化卡片样式
  const savedCardSkin = localStorage.getItem('cardSkin')
  if (savedCardSkin) {
    changeCardSkin(savedCardSkin)
  } else {
    changeCardSkin('default')
  }

  // 监听系统主题变化
  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)
  }
})

// 暴露方法供父组件调用
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-8">
        <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>

      <!-- 卡片样式 -->
      <div class="mb-8">
        <v-label class="text-body-2 font-weight-medium mb-3 ps-1">
          卡片样式
        </v-label>
        <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-label class="text-body-2 font-weight-medium mb-3 ps-1">
          导航布局
        </v-label>
        <div class="layout-options d-flex gap-4 flex-wrap">
          <!-- 水平布局 -->
          <div class="layout-option" :class="{ 'layout-option--active': currentLayout === 'horizontal' }"
            @click="changeLayout('horizontal')">
            <div class="layout-preview">
              <div class="layout-preview__top-header" />
              <div class="layout-preview__horizontal-content" />
            </div>
            <p class="text-body-2 text-center mt-2 mb-0">
              水平布局
            </p>
          </div>

          <!-- 顶部+侧边布局 -->
          <div class="layout-option" :class="{ 'layout-option--active': currentLayout === 'topside' }"
            @click="changeLayout('topside')">
            <div class="layout-preview">
              <div class="layout-preview__sidebar" />
              <div class="layout-preview__content">
                <div class="layout-preview__header" />
                <div class="layout-preview__body" />
              </div>
            </div>
            <p class="text-body-2 text-center mt-2 mb-0">
              侧边布局
            </p>
          </div>
          <div class="layout-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);
    }
  }
}

// 布局选项
.layout-options {
  .layout-option {
    flex: 1;
    cursor: pointer;
    transition: all 0.2s ease;
    padding: 4px;

    .layout-preview {
      width: 100%;
      height: 80px;
      border-radius: 12px;
      border: 2px solid rgba(var(--v-border-color), var(--v-border-opacity));
      overflow: hidden;
      background: rgb(var(--v-theme-surface));
      transition: all 0.2s ease;
      display: flex;

      // 垂直布局
      &__sidebar {
        width: 25%;
        background: rgba(var(--v-theme-primary), 0.1);
      }

      &__content {
        flex: 1;
        display: flex;
        flex-direction: column;
      }

      &__header {
        height: 20%;
        background: rgba(var(--v-theme-on-surface), 0.05);
      }

      &__body {
        flex: 1;
        background: rgb(var(--v-theme-background));
      }

      // 水平布局
      &__top-header {
        height: 25%;
        background: rgba(var(--v-theme-primary), 0.1);
        width: 100%;
      }

      &__horizontal-content {
        flex: 1;
        background: rgb(var(--v-theme-background));
      }

      // 顶部+侧边布局
      &__top-bar {
        height: 20%;
        background: rgba(var(--v-theme-primary), 0.1);
        width: 100%;
      }

      &__bottom-section {
        flex: 1;
        display: flex;
      }

      &__left-sidebar {
        width: 15%;
        background: rgba(var(--v-theme-primary), 0.08);
      }

      &__main-content {
        flex: 1;
        background: rgb(var(--v-theme-background));
      }
    }

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

    &:hover .layout-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>