<template>
  <aside
    class="chat-sidebar"
    :class="{ collapsed: isCollapsed }"
    :style="{ width: isCollapsed ? '0px' : `${sidebarWidth}px` }"
  >
    <div class="sidebar-inner">
      <!-- 头部 -->
      <!-- <div class="sidebar-header">
        <div class="logo">
          <Bot :size="24" class="logo-icon" />
          <span v-show="!isCollapsed" class="logo-text">Kexue AI Chat</span>
        </div>
        <button
          class="collapse-btn"
          @click="toggleSidebar"
          :title="isCollapsed ? '展开侧边栏' : '收起侧边栏'"
        >
          <ChevronLeft :size="18" :class="{ rotated: isCollapsed }" />
        </button>
      </div> -->

      <!-- 模型选择 -->
      <div v-show="!isCollapsed" class="model-selector-section">
        <button class="model-selector" @click="showModelMenu = !showModelMenu">
          <Sparkles :size="16" />
          <span class="model-name-display">{{ currentModel }}</span>
          <ChevronDown :size="14" />
        </button>

        <Transition name="dropdown">
          <div v-if="showModelMenu" class="model-menu">
            <button
              v-for="model in models"
              :key="model.id"
              class="model-option"
              :class="{ active: model.id === currentModelId }"
              @click="selectModel(model.id, model.name)"
            >
              <div class="model-info">
                <span class="model-name">{{ model.name }}</span>
                <span class="model-desc">{{ model.description }}</span>
              </div>
              <Check
                v-if="model.id === currentModelId"
                :size="16"
                class="check-icon"
              />
            </button>
          </div>
        </Transition>
      </div>

      <!-- 新建对话按钮 -->
      <div class="new-chat-section">
        <button class="new-chat-btn" @click="handleNewChat">
          <Plus :size="18" />
          <span>新建对话</span>
        </button>
      </div>

      <!-- 分享按钮 -->
      <ShareButton />

      <!-- 搜索框 -->
      <!-- <div class="search-section">
        <div class="search-box" @click="openSearch">
          <Search :size="16" />
          <span class="search-placeholder">搜索对话...</span>
          <kbd class="search-kbd">⌘K</kbd>
        </div>
      </div> -->

      <!-- 对话列表 -->
      <div class="conversations-section">
        <!-- 置顶对话 -->
        <div v-if="pinnedConversations.length > 0" class="conversation-group">
          <div class="group-header">
            <Pin :size="14" />
            <span>置顶</span>
          </div>
          <div class="group-list">
            <ConversationItem
              v-for="conv in pinnedConversations"
              :key="conv.id"
              :conversation="conv"
              :is-active="conv.id === currentConversationId"
              :is-select-mode="isSelectMode"
              :is-selected="isConversationSelected(conv.id)"
              @select="selectConversation"
              @delete="deleteConversation"
              @rename="renameConversation"
              @toggle-pin="togglePinConversation"
              @toggle-select="toggleConversationSelection"
            />
          </div>
        </div>

        <!-- 最近对话 -->
        <div class="conversation-group">
          <div class="group-header">
            <!-- <Clock :size="14" /> -->
            <span>对话历史</span>
          </div>
          <div class="group-list">
            <ConversationItem
              v-for="conv in recentConversations"
              :key="conv.id"
              :conversation="conv"
              :is-active="conv.id === currentConversationId"
              :is-select-mode="isSelectMode"
              :is-selected="isConversationSelected(conv.id)"
              @select="selectConversation"
              @delete="deleteConversation"
              @rename="renameConversation"
              @toggle-pin="togglePinConversation"
              @toggle-select="toggleConversationSelection"
            />
          </div>
        </div>

        <!-- 空状态 -->
        <div
          v-if="
            pinnedConversations.length === 0 && recentConversations.length === 0
          "
          class="empty-state"
        >
          <MessageSquare :size="40" class="empty-icon" />
          <p>暂无对话</p>
          <span>点击上方按钮开始新对话</span>
        </div>
      </div>

      <!-- 底部操作 -->
      <!-- <div class="sidebar-footer">
        <button class="footer-btn" @click="toggleTheme" title="切换主题">
          <Sun v-if="currentTheme === 'light'" :size="18" />
          <Moon v-else-if="currentTheme === 'dark'" :size="18" />
          <Monitor v-else :size="18" />
        </button>
        键盘快捷键
        <button class="footer-btn" @click="openShortcuts" title="快捷键">
          <Keyboard :size="18" />
        </button>
        dev人员可用
        <button class="footer-btn" @click="openSettings" title="设置">
          <Settings :size="18" />
        </button>
      </div> -->
    </div>

    <!-- 拖拽调整宽度 -->
    <div class="resize-handle" @mousedown="startResize" />
  </aside>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import { useChatStore } from "@/stores/chat";
import { useSettingsStore } from "@/stores/settings";
import { chatApi } from "@/services/api.ts";
import ConversationItem from "./ConversationItem.vue";
import ShareButton from "./ShareButton.vue";
import {
  Plus,
  Pin,
  MessageSquare,
  Sparkles,
  ChevronDown,
  Check,
} from "@/components/icons";

const chatStore = useChatStore();
const settingsStore = useSettingsStore();

const { currentConversationId, pinnedConversations, recentConversations, isSelectMode, selectedConversationIds } =
  storeToRefs(chatStore);

const {
  sidebarCollapsed: isCollapsed,
  sidebarWidth,
} = storeToRefs(settingsStore);

// 模型选择相关
const showModelMenu = ref(false);
const currentModel = ref(localStorage.getItem("modelSelect") || "");
const currentModelId = ref(settingsStore.getSelectedModelId());
const models: any = ref([]);

onMounted(() => {
  chatApi.getModels().then((res: any) => {
    models.value = res;
    // 初始化模型显示名称
    const model = models.value?.find((m: any) => m.id === currentModelId.value);
    if (model) {
      currentModel.value = model.name;
    } else if (models.value.length > 0) {
      currentModel.value = models.value[0].name;
      currentModelId.value = models.value[0].id;
    }
    localStorage.setItem("modelSelect", currentModel.value);
  });
});

function selectModel(modelId: string, modelName: string) {
  currentModel.value = modelName;
  currentModelId.value = modelId;
  localStorage.setItem("modelSelect", modelName);
  settingsStore.setSelectedModelId(modelId); // 更新选中的模型 ID
  showModelMenu.value = false;

  // 切换模型时重置搜索和思考参数
  localStorage.setItem("isDeepSearch", "false");
  localStorage.setItem("isDeepThinking", "false");
  localStorage.setItem("isWebSearch", "false");
}

// 方法
function handleNewChat() {
  chatStore.createConversation();
}

function selectConversation(id: string) {
  chatStore.selectConversation(id);
}

function deleteConversation(id: string) {
  chatStore.deleteConversation(id);
}

function renameConversation(id: string, title: string) {
  chatStore.renameConversation(id, title);
}

function togglePinConversation(id: string) {
  chatStore.togglePinConversation(id);
}

function toggleConversationSelection(id: string) {
  chatStore.toggleConversationSelection(id);
}

function isConversationSelected(id: string): boolean {
  return selectedConversationIds.value.includes(id);
}

// 拖拽调整宽度
const isResizing = ref(false);

function startResize(e: MouseEvent) {
  isResizing.value = true;
  const startX = e.clientX;
  const startWidth = sidebarWidth.value;

  const handleMouseMove = (e: MouseEvent) => {
    const diff = e.clientX - startX;
    settingsStore.setSidebarWidth(startWidth + diff);
  };

  const handleMouseUp = () => {
    isResizing.value = false;
    document.removeEventListener("mousemove", handleMouseMove);
    document.removeEventListener("mouseup", handleMouseUp);
  };

  document.addEventListener("mousemove", handleMouseMove);
  document.addEventListener("mouseup", handleMouseUp);
}

// 点击外部关闭模型菜单
function handleClickOutside(event: MouseEvent) {
  const target = event.target as HTMLElement;
  if (!target.closest(".model-selector") && !target.closest(".model-menu")) {
    showModelMenu.value = false;
  }
}

if (typeof window !== "undefined") {
  document.addEventListener("click", handleClickOutside);
}
</script>

<style lang="scss" scoped>
.chat-sidebar {
  position: relative;
  height: 100vh;
  background: #ffffff;
  transition: width 0.3s ease;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 10px;
  border-radius: 15px;

  .dark & {
    background: #1e1e2e;
    border-right-color: #2d2d3d;
  }

  &.collapsed {
    .sidebar-inner {
      opacity: 0;
      pointer-events: none;
    }
  }
}

.sidebar-inner {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  transition: opacity 0.2s ease;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;

  .dark & {
    border-bottom-color: #2d2d3d;
  }
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo-icon {
  color: #3b82f6;
}

.logo-text {
  font-size: 18px;
  font-weight: 700;
  color: #1f2937;

  .dark & {
    color: #f3f4f6;
  }
}

.collapse-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 8px;
  background: transparent;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(0, 0, 0, 0.05);
    color: #374151;

    .dark & {
      background: rgba(255, 255, 255, 0.05);
      color: #e5e7eb;
    }
  }

  svg {
    transition: transform 0.3s ease;

    &.rotated {
      transform: rotate(180deg);
    }
  }
}

.model-selector-section {
  position: relative;
  padding: 12px 16px 6px;
}

.model-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  padding: 6px 12px;
  border-radius: 10px;
  background: #f3f4f5;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;

  .dark & {
    background: #2d2d3d;
    border-color: #374151;
    color: #e5e7eb;
  }

  &:hover {
    border-color: #3b82f6;
  }

  svg:first-child {
    color: #8b5cf6;
    flex-shrink: 0;
  }

  .model-name-display {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.model-menu {
  position: absolute;
  top: calc(100% + 8px);
  left: 16px;
  right: 16px;
  min-width: 200px;
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 14px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  z-index: 100;

  .dark & {
    background: #1e1e2e;
    border-color: #2d2d3d;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
  }
}

.model-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 12px 14px;
  border: none;
  border-radius: 10px;
  background: transparent;
  text-align: left;
  cursor: pointer;
  transition: all 0.15s ease;

  &:hover {
    background: #f3f4f6;

    .dark & {
      background: #2d2d3d;
    }
  }

  &.active {
    background: rgba(59, 130, 246, 0.1);

    .model-name {
      color: #3b82f6;
    }
  }
}

.model-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  overflow: hidden;
}

.model-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  .dark & {
    color: #f3f4f6;
  }
}

.model-desc {
  font-size: 12px;
  color: #9ca3af;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.check-icon {
  color: #3b82f6;
  flex-shrink: 0;
}

// 下拉动画
.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.2s ease;
}

.dropdown-enter-from,
.dropdown-leave-to {
  opacity: 0;
  transform: translateY(-8px);
}

.new-chat-section {
  padding: 6px 16px;
}

.new-chat-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 6px 12px;
  border-radius: 12px;
  background: #f3f4f5;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;

  .dark & {
    background: #2d2d3d;
    color: #e5e7eb;
    &:hover {
      background: #0475ed;
      color: #e5e7eb;
    }
  }

  &:hover {
    background: #000f33;
    color: #e5e7eb;
  }
}

.search-section {
  padding: 6px 16px 12px;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.03);
  color: #9ca3af;
  cursor: pointer;
  transition: all 0.2s ease;

  .dark & {
    background: rgba(255, 255, 255, 0.03);
  }

  &:hover {
    background: rgba(0, 0, 0, 0.06);

    .dark & {
      background: rgba(255, 255, 255, 0.06);
    }
  }
}

.search-placeholder {
  flex: 1;
  font-size: 13px;
}

.search-kbd {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.06);

  .dark & {
    background: rgba(255, 255, 255, 0.1);
  }
}

.conversations-section {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 12px;
}

.conversation-group {
  margin-bottom: 8px;
}

.group-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 20px;
  font-size: 12px;
  font-weight: 600;
  color: #9ca3af;
  text-transform: uppercase;
  letter-spacing: 0.5px;

  .dark & {
    color: #6b7280;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;

  .empty-icon {
    color: #d1d5db;
    margin-bottom: 12px;

    .dark & {
      color: #4b5563;
    }
  }

  p {
    margin: 0 0 4px;
    font-size: 14px;
    font-weight: 500;
    color: #6b7280;
  }

  span {
    font-size: 12px;
    color: #9ca3af;
  }
}

.sidebar-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid #e2e8f0;

  .dark & {
    border-top-color: #2d2d3d;
  }
}

.footer-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 10px;
  background: transparent;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(0, 0, 0, 0.05);
    color: #374151;

    .dark & {
      background: rgba(255, 255, 255, 0.05);
      color: #e5e7eb;
    }
  }
}

.resize-handle {
  position: absolute;
  top: 0;
  right: -3px;
  width: 6px;
  height: 100%;
  cursor: col-resize;
  z-index: 10;
}
</style>
