<script setup lang="ts">
import { ref } from 'vue'
import { useAgentsStore } from '../../stores/agents'
import type { ToolEntry } from '../../stores/agents'

const store = useAgentsStore()
const newRuleFor = ref<string | null>(null)
const newRuleValue = ref('')

function statusColor(status: string): string {
  if (status === 'allow') return '#22c55e'
  if (status === 'deny') return '#ef4444'
  return 'var(--text-muted)'
}

function statusLabel(status: string): string {
  if (status === 'allow') return 'Allow'
  if (status === 'deny') return 'Deny'
  return 'Ask'
}

function submitRule(toolKey: string) {
  if (newRuleValue.value.trim()) {
    store.addToolRule(toolKey, newRuleValue.value.trim())
    newRuleValue.value = ''
    newRuleFor.value = null
  }
}

function isParameterizable(name: string): boolean {
  return ['Bash', 'WebFetch', 'Skill', 'WebSearch'].includes(name)
}
</script>

<template>
  <div class="tools-manager">
    <!-- Header -->
    <div class="tools-header">
      <div class="tools-header-left">
        <h3>Tool Permissions</h3>
        <span class="tools-count">{{ store.filteredTools.length }} tools</span>
        <span v-if="store.configFile" class="config-path">{{ store.configFile }}</span>
      </div>
      <div class="tools-header-right">
        <input
          type="text"
          class="tools-search"
          placeholder="Filter tools..."
          v-model="store.toolsFilter"
        />
        <button
          class="btn btn-primary"
          :disabled="!store.configDirty || store.saving"
          @click="store.savePermissions()"
        >{{ store.saving ? 'Saving...' : 'Save Permissions' }}</button>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="store.toolsLoading" class="tools-loading">Loading tools...</div>

    <!-- Error -->
    <div v-if="store.error" class="tools-error">{{ store.error }}</div>

    <!-- Tools list -->
    <div v-if="!store.toolsLoading" class="tools-scroll">
      <!-- Base tools -->
      <div v-if="store.toolsByCategory.base.length" class="tool-group">
        <div class="tool-group-header">
          <span class="tool-group-label">Base Tools</span>
          <span class="tool-group-count">{{ store.toolsByCategory.base.length }}</span>
        </div>

        <div class="tool-cards">
          <div v-for="tool in store.toolsByCategory.base" :key="tool.fullKey" class="tool-card">
            <div class="tool-card-main">
              <div class="tool-info">
                <span class="tool-name">{{ tool.name }}</span>
                <span class="tool-badge base">base</span>
              </div>
              <button
                class="status-toggle"
                :style="{ '--status-color': statusColor(tool.status) }"
                @click="store.cycleToolStatus(tool.fullKey)"
                :title="`Click to cycle: ${tool.status}`"
              >
                <span class="status-dot" :class="tool.status"></span>
                <span class="status-text">{{ statusLabel(tool.status) }}</span>
              </button>
            </div>

            <!-- Rules for parameterizable tools -->
            <div v-if="isParameterizable(tool.name) && tool.status !== 'ask'" class="tool-rules">
              <div v-for="(rule, idx) in tool.rules" :key="idx" class="rule-item">
                <code>{{ tool.name }}({{ rule }})</code>
                <button class="rule-remove" @click="store.removeToolRule(tool.fullKey, rule)">&times;</button>
              </div>
              <div v-if="newRuleFor === tool.fullKey" class="rule-add-form">
                <input
                  type="text"
                  class="rule-input"
                  v-model="newRuleValue"
                  placeholder="e.g. git:* or domain:example.com"
                  @keydown.enter="submitRule(tool.fullKey)"
                  @keydown.escape="newRuleFor = null"
                />
                <button class="btn-sm" @click="submitRule(tool.fullKey)">Add</button>
              </div>
              <button v-else class="rule-add-btn" @click="newRuleFor = tool.fullKey; newRuleValue = ''">
                + Add rule
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- MCP tools grouped by server -->
      <div
        v-for="(tools, server) in store.toolsByCategory.mcpGroups"
        :key="server"
        class="tool-group"
      >
        <div class="tool-group-header">
          <span class="tool-group-label">MCP: {{ server }}</span>
          <span class="tool-group-count">{{ tools.length }}</span>
        </div>

        <div class="tool-cards">
          <div v-for="tool in tools" :key="tool.fullKey" class="tool-card">
            <div class="tool-card-main">
              <div class="tool-info">
                <span class="tool-name">{{ tool.name }}</span>
                <span class="tool-badge mcp">mcp</span>
                <span v-if="tool.host" class="tool-host">{{ tool.host }}</span>
              </div>
              <button
                class="status-toggle"
                :style="{ '--status-color': statusColor(tool.status) }"
                @click="store.cycleToolStatus(tool.fullKey)"
                :title="`Click to cycle: ${tool.status}`"
              >
                <span class="status-dot" :class="tool.status"></span>
                <span class="status-text">{{ statusLabel(tool.status) }}</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Empty state -->
      <div v-if="!store.toolsByCategory.base.length && !Object.keys(store.toolsByCategory.mcpGroups).length" class="tools-empty">
        <p>No tools found</p>
        <span>Tool permissions will appear here when configured</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.tools-manager {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

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

.tools-header-left {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.tools-header-left h3 {
  margin: 0;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-primary);
}

.tools-count {
  font-size: 0.6875rem;
  color: var(--text-muted);
  padding: 0.125rem 0.5rem;
  background: var(--bg-hover);
  border-radius: 999px;
}

.config-path {
  font-size: 0.6875rem;
  color: var(--text-muted);
  font-family: 'Consolas', monospace;
}

.tools-header-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.tools-search {
  padding: 0.3125rem 0.75rem;
  font-size: 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--bg-primary);
  color: var(--text-primary);
  outline: none;
  width: 200px;
}

.tools-search:focus {
  border-color: #6366f1;
}

.tools-loading,
.tools-empty {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  color: var(--text-muted);
  font-size: 0.8125rem;
}

.tools-empty span {
  font-size: 0.6875rem;
  opacity: 0.6;
}

.tools-error {
  padding: 0.625rem 1.25rem;
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
  font-size: 0.8125rem;
  border-bottom: 1px solid rgba(239, 68, 68, 0.2);
}

.tools-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 1.25rem;
}

/* Tool groups */
.tool-group {
  margin-bottom: 1.5rem;
}

.tool-group-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.tool-group-label {
  font-size: 0.6875rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: var(--text-secondary);
}

.tool-group-count {
  font-size: 0.625rem;
  padding: 0.0625rem 0.375rem;
  background: var(--bg-hover);
  border-radius: 999px;
  color: var(--text-muted);
}

/* Tool cards */
.tool-cards {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

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

.tool-card-main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0.75rem;
  gap: 0.5rem;
}

.tool-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: 0;
}

.tool-name {
  font-size: 0.8125rem;
  font-weight: 500;
  color: var(--text-primary);
  font-family: 'Consolas', monospace;
}

.tool-badge {
  font-size: 0.5625rem;
  font-weight: 600;
  padding: 0.0625rem 0.375rem;
  border-radius: 999px;
  text-transform: uppercase;
}

.tool-badge.base {
  background: rgba(99, 102, 241, 0.12);
  color: #6366f1;
}

.tool-badge.mcp {
  background: rgba(139, 92, 246, 0.12);
  color: #8b5cf6;
}

.tool-host {
  font-size: 0.625rem;
  color: var(--text-muted);
  font-family: 'Consolas', monospace;
}

/* Status toggle */
.status-toggle {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.25rem 0.625rem;
  background: transparent;
  border: 1px solid var(--border-color);
  border-radius: 999px;
  cursor: pointer;
  transition: all 0.15s;
  flex-shrink: 0;
}

.status-toggle:hover {
  background: var(--bg-hover);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  transition: background 0.15s;
}

.status-dot.allow { background: #22c55e; }
.status-dot.deny { background: #ef4444; }
.status-dot.ask { background: var(--text-muted); }

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

/* Rules */
.tool-rules {
  padding: 0.375rem 0.75rem 0.5rem;
  border-top: 1px solid var(--border-color);
  background: var(--bg-primary);
}

.rule-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.1875rem 0;
}

.rule-item code {
  font-size: 0.6875rem;
  color: var(--text-secondary);
  font-family: 'Consolas', monospace;
}

.rule-remove {
  background: none;
  border: none;
  color: var(--text-muted);
  cursor: pointer;
  font-size: 0.875rem;
  padding: 0 0.25rem;
  line-height: 1;
}

.rule-remove:hover {
  color: #ef4444;
}

.rule-add-form {
  display: flex;
  gap: 0.375rem;
  margin-top: 0.25rem;
}

.rule-input {
  flex: 1;
  padding: 0.25rem 0.5rem;
  font-size: 0.6875rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background: var(--bg-secondary);
  color: var(--text-primary);
  outline: none;
  font-family: 'Consolas', monospace;
}

.rule-input:focus {
  border-color: #6366f1;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.6875rem;
  background: #6366f1;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.rule-add-btn {
  background: none;
  border: none;
  color: #6366f1;
  font-size: 0.6875rem;
  cursor: pointer;
  padding: 0.25rem 0;
}

.rule-add-btn:hover {
  text-decoration: underline;
}

.btn {
  padding: 0.3125rem 0.75rem;
  font-size: 0.75rem;
  font-weight: 500;
  border-radius: 6px;
  border: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.15s;
}

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

.btn-primary {
  background: #6366f1;
  color: white;
  border-color: #6366f1;
}

.btn-primary:hover:not(:disabled) {
  background: #4f46e5;
  border-color: #4f46e5;
}
</style>
