<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useToolsStore } from '../stores/tools'
import {
  activateCategory,
  deactivateCategory,
  syncStoreWithActiveTools
} from '../services/toolRegistry'
import { CATEGORY_INFO, type ToolCategory } from '../services/tools/toolDefinitions'

const toolsStore = useToolsStore()
const { activeTools, pinnedTools } = storeToRefs(toolsStore)
const isOpen = ref(false)

// Category to tools mapping
const categoryTools: Record<ToolCategory, string[]> = {
  global: ['get_current_page', 'navigate_to', 'list_available_tools', 'activate_tool', 'deactivate_tool', 'pin_tool'],
  canvas: ['render_html', 'render_vue_component'],
  component: ['save_vue_component', 'load_vue_component', 'list_vue_components', 'delete_vue_component'],
  theme: ['get_design_tokens', 'get_active_theme', 'set_theme_variable', 'save_theme', 'list_themes', 'switch_theme', 'reset_theme'],
  database: ['list_tables', 'get_table_schema', 'get_table_data', 'get_database_stats', 'execute_query'],
  source: ['get_repo_info', 'list_repo_files', 'read_repo_file', 'search_repo_code'],
  project: ['list_canvases', 'create_canvas', 'get_canvas', 'update_canvas', 'delete_canvas', 'clone_canvas', 'add_component_to_canvas', 'remove_component_from_canvas', 'get_canvas_components'],
  terminal: ['terminal_open', 'terminal_close', 'terminal_toggle', 'terminal_move', 'terminal_resize']
}

const categories = computed(() => {
  return Object.entries(CATEGORY_INFO).map(([key, info]) => {
    const tools = categoryTools[key as ToolCategory]
    const activeCount = tools.filter(t => activeTools.value.includes(t)).length
    const pinnedCount = tools.filter(t => pinnedTools.value.includes(t)).length
    const allPinned = tools.every(t => pinnedTools.value.includes(t))

    return {
      key: key as ToolCategory,
      ...info,
      tools,
      activeCount,
      totalCount: tools.length,
      pinnedCount,
      allPinned
    }
  })
})

const totalPinned = computed(() => pinnedTools.value.length)
const totalActive = computed(() => activeTools.value.length)

function toggleDropdown() {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    syncStoreWithActiveTools()
  }
}

function closeDropdown(e: MouseEvent) {
  const target = e.target as HTMLElement
  if (!target.closest('.tools-dropdown-container')) {
    isOpen.value = false
  }
}

async function handlePinCategory(category: ToolCategory) {
  const tools = categoryTools[category]
  const allPinned = tools.every(t => pinnedTools.value.includes(t))

  if (allPinned) {
    // Unpin all tools in category
    for (const tool of tools) {
      toolsStore.unpinTool(tool)
    }
  } else {
    // Pin all tools in category and activate them
    for (const tool of tools) {
      toolsStore.pinTool(tool)
    }
    await activateCategory(category)
  }
  syncStoreWithActiveTools()
}

async function handleActivateCategory(category: ToolCategory) {
  await activateCategory(category)
  syncStoreWithActiveTools()
}

function handleDeactivateCategory(category: ToolCategory) {
  deactivateCategory(category)
  syncStoreWithActiveTools()
}

onMounted(() => {
  document.addEventListener('click', closeDropdown)
})

onUnmounted(() => {
  document.removeEventListener('click', closeDropdown)
})
</script>

<template>
  <div class="tools-dropdown-container">
    <button class="dropdown-trigger" @click.stop="toggleDropdown" title="Herramientas MCP">
      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
      </svg>
      <span>Tools</span>
      <span v-if="totalPinned > 0" class="badge">{{ totalPinned }}</span>
      <svg class="chevron" :class="{ open: isOpen }" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polyline points="6 9 12 15 18 9"/>
      </svg>
    </button>

    <div v-if="isOpen" class="dropdown-menu" @click.stop>
      <div class="dropdown-header">
        <span class="header-title">Tool Categories</span>
        <span class="header-stats">{{ totalActive }} active</span>
      </div>

      <div class="categories-list">
        <div
          v-for="cat in categories"
          :key="cat.key"
          class="category-item"
          :style="{ '--cat-color': cat.color }"
        >
          <div class="category-info">
            <div class="category-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path :d="cat.icon"/>
              </svg>
            </div>
            <div class="category-details">
              <span class="category-name">{{ cat.label }}</span>
              <span class="category-count">{{ cat.activeCount }}/{{ cat.totalCount }} active</span>
            </div>
          </div>

          <div class="category-actions">
            <button
              class="action-btn pin-btn"
              :class="{ pinned: cat.allPinned }"
              @click="handlePinCategory(cat.key)"
              :title="cat.allPinned ? 'Unpin category' : 'Pin category (keep active)'"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M12 17v5"/>
                <path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v4.76z"/>
              </svg>
            </button>
            <button
              class="action-btn activate-btn"
              @click="handleActivateCategory(cat.key)"
              title="Activate all"
              :disabled="cat.activeCount === cat.totalCount"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="20 6 9 17 4 12"/>
              </svg>
            </button>
            <button
              class="action-btn deactivate-btn"
              @click="handleDeactivateCategory(cat.key)"
              title="Deactivate all"
              :disabled="cat.activeCount === 0 || cat.allPinned"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"/>
                <line x1="6" y1="6" x2="18" y2="18"/>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <div class="dropdown-footer">
        <RouterLink to="/tools" class="manage-link" @click="isOpen = false">
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="3"/>
            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
          </svg>
          Manage all tools
        </RouterLink>
      </div>
    </div>
  </div>
</template>

<style scoped>
.tools-dropdown-container {
  position: relative;
}

.dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: var(--bg-hover);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  color: var(--text-secondary);
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s ease;
}

.dropdown-trigger:hover {
  background: var(--bg-tertiary, rgba(255,255,255,0.1));
  color: var(--text-primary);
}

.badge {
  background: #f59e0b;
  color: white;
  font-size: 0.7rem;
  font-weight: 600;
  padding: 0.125rem 0.375rem;
  border-radius: 9999px;
  min-width: 18px;
  text-align: center;
}

.chevron {
  transition: transform 0.2s ease;
}

.chevron.open {
  transform: rotate(180deg);
}

.dropdown-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  min-width: 280px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
  z-index: 1000;
  overflow: hidden;
}

.dropdown-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--border-color);
}

.header-title {
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--text-secondary);
}

.header-stats {
  font-size: 0.7rem;
  color: var(--text-muted);
}

.categories-list {
  padding: 0.5rem;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0.625rem;
  border-radius: 8px;
  margin-bottom: 0.25rem;
  transition: background 0.15s;
}

.category-item:hover {
  background: var(--bg-hover);
}

.category-info {
  display: flex;
  align-items: center;
  gap: 0.625rem;
}

.category-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  background: var(--bg-primary);
  border-radius: 6px;
  color: var(--cat-color);
}

.category-details {
  display: flex;
  flex-direction: column;
  gap: 0.1rem;
}

.category-name {
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-primary);
}

.category-count {
  font-size: 0.65rem;
  color: var(--text-muted);
}

.category-actions {
  display: flex;
  gap: 0.25rem;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  border: 1px solid var(--border-color);
  border-radius: 5px;
  background: transparent;
  color: var(--text-muted);
  cursor: pointer;
  transition: all 0.15s;
}

.action-btn:hover:not(:disabled) {
  background: var(--bg-primary);
  color: var(--text-primary);
}

.action-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.pin-btn:hover:not(:disabled) {
  color: #f59e0b;
  border-color: #f59e0b;
}

.pin-btn.pinned {
  color: #f59e0b;
  background: rgba(245, 158, 11, 0.15);
  border-color: #f59e0b;
}

.activate-btn:hover:not(:disabled) {
  color: #10b981;
  border-color: #10b981;
}

.deactivate-btn:hover:not(:disabled) {
  color: #ef4444;
  border-color: #ef4444;
}

.dropdown-footer {
  padding: 0.5rem;
  border-top: 1px solid var(--border-color);
}

.manage-link {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 0.5rem;
  border-radius: 6px;
  color: var(--text-secondary);
  text-decoration: none;
  font-size: 0.8rem;
  transition: all 0.15s;
}

.manage-link:hover {
  background: var(--bg-hover);
  color: var(--accent);
}
</style>
