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

const toolsStore = useToolsStore()
const { activeTools: activeToolsSet } = storeToRefs(toolsStore)

// State
const currentPage = ref<string | null>(null)
const isInitialized = ref(false)
const refreshInterval = ref<number | null>(null)
const activeTab = ref<'active' | 'all'>('all')
const expandedCategories = ref<Set<string>>(new Set(['global', 'canvas', 'component']))

// Computed - use reactive store
const activeTools = computed(() => Array.from(activeToolsSet.value))

const toolsByCategory = computed(() => {
  const categories: Record<string, ToolMeta[]> = {}

  for (const category of Object.keys(CATEGORY_INFO)) {
    categories[category] = []
  }

  for (const tool of ALL_TOOL_METAS) {
    categories[tool.category].push(tool)
  }

  // Sort each category by name
  for (const category of Object.keys(categories)) {
    categories[category].sort((a, b) => a.name.localeCompare(b.name))
  }

  return categories
})

const totalTools = computed(() => ALL_TOOL_METAS.length)
const totalActive = computed(() => activeTools.value.length)
const totalPinned = computed(() => toolsStore.getPinnedToolNames().length)

function refresh() {
  syncStoreWithActiveTools()
  currentPage.value = getCurrentPage()
  isInitialized.value = isRegistryInitialized()
}

function toggleCategory(category: string) {
  if (expandedCategories.value.has(category)) {
    expandedCategories.value.delete(category)
  } else {
    expandedCategories.value.add(category)
  }
}

async function handleToggleTool(tool: ToolMeta) {
  if (activeTools.value.includes(tool.name)) {
    deactivateTool(tool.name)
  } else {
    await activateTool(tool.name)
  }
  refresh()
}

async function handleTogglePin(tool: ToolMeta) {
  toolsStore.togglePin(tool.name)
  // Si pinneamos una tool inactiva, activarla
  if (toolsStore.isToolPinned(tool.name) && !activeTools.value.includes(tool.name)) {
    await activateTool(tool.name)
  }
  refresh()
}

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

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

function isToolActive(name: string): boolean {
  return activeTools.value.includes(name)
}

function isToolPinned(name: string): boolean {
  return toolsStore.isToolPinned(name)
}

function getCategoryStats(category: string) {
  const tools = toolsByCategory.value[category]
  if (!tools) return { active: 0, total: 0 }
  const activeCount = tools.filter(t => activeTools.value.includes(t.name)).length
  return {
    active: activeCount,
    total: tools.length
  }
}

onMounted(() => {
  refresh()
  refreshInterval.value = window.setInterval(refresh, 2000)
})

onUnmounted(() => {
  if (refreshInterval.value) {
    window.clearInterval(refreshInterval.value)
  }
})
</script>

<template>
  <div class="tools-page">
    <header class="page-header">
      <div class="header-content">
        <h1>Tool Registry</h1>
        <p class="subtitle">Manage MCP tools activation and persistence</p>
      </div>
      <button class="refresh-btn" @click="refresh" title="Refresh">
        <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="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/>
          <path d="M21 3v5h-5"/>
        </svg>
      </button>
    </header>

    <div class="status-bar">
      <div class="status-item">
        <span class="status-label">Status</span>
        <span class="status-value" :class="{ active: isInitialized }">
          {{ isInitialized ? 'Ready' : 'Not Initialized' }}
        </span>
      </div>
      <div class="status-item">
        <span class="status-label">Current Page</span>
        <span class="status-value page">{{ currentPage || 'None' }}</span>
      </div>
      <div class="status-item">
        <span class="status-label">Active</span>
        <span class="status-value count">{{ totalActive }} / {{ totalTools }}</span>
      </div>
      <div class="status-item">
        <span class="status-label">Pinned</span>
        <span class="status-value pinned">{{ totalPinned }}</span>
      </div>
    </div>

    <div class="tabs">
      <button
        :class="{ active: activeTab === 'all' }"
        @click="activeTab = 'all'"
      >
        All Tools
      </button>
      <button
        :class="{ active: activeTab === 'active' }"
        @click="activeTab = 'active'"
      >
        Active Only
      </button>
    </div>

    <main class="content">
      <div class="categories">
        <div
          v-for="(info, category) in CATEGORY_INFO"
          :key="category"
          class="category-card"
          :class="{ collapsed: !expandedCategories.has(category) }"
        >
          <div
            class="category-header"
            :style="{ '--cat-color': info.color }"
            @click="toggleCategory(category)"
          >
            <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="info.icon"/>
            </svg>
            <h3>{{ info.label }}</h3>
            <span class="tool-count">
              {{ getCategoryStats(category).active }} / {{ getCategoryStats(category).total }}
            </span>
            <div class="category-actions" @click.stop>
              <button
                class="cat-btn activate"
                @click="handleActivateCategory(category as ToolCategory)"
                title="Activate all"
              >
                <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="cat-btn deactivate"
                @click="handleDeactivateCategory(category as ToolCategory)"
                title="Deactivate all"
              >
                <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>
            <svg
              class="chevron"
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <polyline points="6 9 12 15 18 9"/>
            </svg>
          </div>

          <div class="tool-list" v-show="expandedCategories.has(category)">
            <template v-for="tool in toolsByCategory[category] || []" :key="tool.name">
              <!-- Filter by activeTab -->
              <div
                v-if="activeTab === 'all' || isToolActive(tool.name)"
                class="tool-item"
                :class="{ active: isToolActive(tool.name), inactive: !isToolActive(tool.name) }"
              >
                <div class="tool-info">
                  <span class="tool-name">{{ tool.name }}</span>
                  <span class="tool-desc">{{ tool.description }}</span>
                </div>
                <div class="tool-actions">
                  <button
                    class="pin-btn"
                    :class="{ pinned: isToolPinned(tool.name) }"
                    @click="handleTogglePin(tool)"
                    :title="isToolPinned(tool.name) ? 'Unpin' : 'Pin (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="toggle-btn"
                    :class="{ active: isToolActive(tool.name) }"
                    @click="handleToggleTool(tool)"
                    :disabled="isToolPinned(tool.name)"
                    :title="isToolActive(tool.name) ? 'Deactivate' : 'Activate'"
                  >
                    <svg v-if="isToolActive(tool.name)" 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>
                    <svg v-else 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="10"/>
                    </svg>
                  </button>
                </div>
              </div>
            </template>

            <!-- Empty state for active tab -->
            <div
              v-if="activeTab === 'active' && getCategoryStats(category).active === 0"
              class="empty-category"
            >
              No active tools in this category
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
.tools-page {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--bg-primary);
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.25rem 1.5rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
}

.header-content h1 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-primary);
}

.subtitle {
  margin: 0.2rem 0 0;
  font-size: 0.8rem;
  color: var(--text-secondary);
}

.refresh-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

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

.status-bar {
  display: flex;
  gap: 1.5rem;
  padding: 0.75rem 1.5rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
}

.status-item {
  display: flex;
  flex-direction: column;
  gap: 0.15rem;
}

.status-label {
  font-size: 0.65rem;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--text-muted);
}

.status-value {
  font-size: 0.8rem;
  font-weight: 500;
  color: var(--text-secondary);
}

.status-value.active { color: #10b981; }
.status-value.page { color: #6366f1; font-family: monospace; }
.status-value.count { color: var(--text-primary); }
.status-value.pinned { color: #f59e0b; }

.tabs {
  display: flex;
  gap: 0.25rem;
  padding: 0.5rem 1.5rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
}

.tabs button {
  padding: 0.4rem 0.75rem;
  background: transparent;
  border: none;
  border-radius: 5px;
  color: var(--text-secondary);
  font-size: 0.8rem;
  cursor: pointer;
  transition: all 0.15s;
}

.tabs button:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.tabs button.active {
  background: var(--accent-muted);
  color: var(--accent);
}

.content {
  flex: 1;
  overflow: auto;
  padding: 1rem 1.5rem;
}

.categories {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.category-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}

.category-header {
  display: flex;
  align-items: center;
  gap: 0.6rem;
  padding: 0.75rem 1rem;
  background: var(--bg-primary);
  border-bottom: 1px solid var(--border-color);
  color: var(--cat-color);
  cursor: pointer;
  user-select: none;
}

.category-card.collapsed .category-header {
  border-bottom: none;
}

.category-header h3 {
  margin: 0;
  font-size: 0.85rem;
  font-weight: 600;
  flex: 1;
}

.tool-count {
  font-size: 0.7rem;
  font-weight: 500;
  padding: 0.15rem 0.4rem;
  background: var(--bg-secondary);
  border-radius: 8px;
  color: var(--text-secondary);
}

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

.cat-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.cat-btn:hover {
  background: var(--bg-hover);
}

.cat-btn.activate:hover {
  color: #10b981;
  border-color: #10b981;
}

.cat-btn.deactivate:hover {
  color: #ef4444;
  border-color: #ef4444;
}

.chevron {
  color: var(--text-muted);
  transition: transform 0.2s;
}

.category-card.collapsed .chevron {
  transform: rotate(-90deg);
}

.tool-list {
  padding: 0.25rem 0;
}

.tool-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 1rem;
  transition: background 0.15s;
}

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

.tool-item.inactive {
  opacity: 0.6;
}

.tool-item.inactive:hover {
  opacity: 1;
}

.tool-info {
  display: flex;
  flex-direction: column;
  gap: 0.1rem;
  flex: 1;
  min-width: 0;
}

.tool-name {
  font-family: monospace;
  font-size: 0.8rem;
  color: var(--text-primary);
}

.tool-desc {
  font-size: 0.7rem;
  color: var(--text-muted);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tool-actions {
  display: flex;
  gap: 0.35rem;
  margin-left: 0.5rem;
}

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

.pin-btn:hover {
  color: #f59e0b;
  border-color: #f59e0b;
}

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

.toggle-btn:hover {
  color: var(--text-primary);
  border-color: var(--text-secondary);
}

.toggle-btn.active {
  color: #10b981;
  background: rgba(16, 185, 129, 0.15);
  border-color: #10b981;
}

.toggle-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.empty-category {
  padding: 0.75rem 1rem;
  font-size: 0.75rem;
  color: var(--text-muted);
  font-style: italic;
}
</style>
