<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue"
import { getMcpService, type McpTool, type McpExecutionResult, type McpConnectionStatus } from "@/services/McpService"
import ToolCard from "./ToolCard.vue"
import ExecutionLog from "./ExecutionLog.vue"

const mcpService = getMcpService()

const connectionStatus = ref<McpConnectionStatus>("disconnected")
const tools = ref<McpTool[]>([])
const executions = ref<McpExecutionResult[]>([])
const serverUrl = ref("http://localhost:3006")
const searchQuery = ref("")
const activeTab = ref<"tools" | "log" | "quick">("quick")
const isConnecting = ref(false)

const filteredTools = computed(() => {
  if (!searchQuery.value) return tools.value
  const q = searchQuery.value.toLowerCase()
  return tools.value.filter(
    (t) =>
      t.name.toLowerCase().includes(q) ||
      t.description.toLowerCase().includes(q)
  )
})

const statusColor = computed(() => {
  switch (connectionStatus.value) {
    case "connected": return "#22c55e"
    case "connecting": return "#f59e0b"
    case "error": return "#ef4444"
    default: return "#6b7280"
  }
})

const statusText = computed(() => {
  switch (connectionStatus.value) {
    case "connected": return "Connected"
    case "connecting": return "Connecting..."
    case "error": return "Error"
    default: return "Disconnected"
  }
})

let unsubStatus: (() => void) | null = null
let unsubTools: (() => void) | null = null
let unsubExec: (() => void) | null = null

onMounted(() => {
  connectionStatus.value = mcpService.getStatus()
  tools.value = mcpService.getTools()
  executions.value = mcpService.getExecutions()

  unsubStatus = mcpService.onStatusChange((s) => {
    connectionStatus.value = s
    isConnecting.value = s === "connecting"
  })
  unsubTools = mcpService.onToolsUpdate((t) => {
    tools.value = [...t]
  })
  unsubExec = mcpService.onExecution(() => {
    executions.value = [...mcpService.getExecutions()]
  })
})

onUnmounted(() => {
  unsubStatus?.()
  unsubTools?.()
  unsubExec?.()
})

async function toggleConnection() {
  if (connectionStatus.value === "connected") {
    await mcpService.disconnect()
  } else {
    isConnecting.value = true
    await mcpService.connect()
  }
}

async function handleToolExecute(toolName: string, args: Record<string, any>) {
  activeTab.value = "log"
  await mcpService.callTool(toolName, args)
}

function clearLog() {
  mcpService.clearExecutions()
  executions.value = []
}

// Quick Actions
const quickActions = [
  {
    icon: "🔍",
    label: "Search Nodes",
    tool: "search_nodes",
    defaultArgs: { query: "webhook", limit: 5 },
  },
  {
    icon: "📋",
    label: "List Workflows",
    tool: "n8n_list_workflows",
    defaultArgs: {},
  },
  {
    icon: "❤️",
    label: "Health Check",
    tool: "n8n_health_check",
    defaultArgs: {},
  },
  {
    icon: "📖",
    label: "Tools Doc",
    tool: "tools_documentation",
    defaultArgs: {},
  },
  {
    icon: "🔎",
    label: "Search Templates",
    tool: "search_templates",
    defaultArgs: { query: "automation", limit: 3 },
  },
  {
    icon: "✅",
    label: "Validate Workflow",
    tool: "validate_workflow",
    defaultArgs: {},
  },
]

async function runQuickAction(action: (typeof quickActions)[0]) {
  activeTab.value = "log"
  await mcpService.callTool(action.tool, action.defaultArgs)
}
</script>

<template>
  <div class="n8n-panel">
    <!-- Header -->
    <div class="panel-header">
      <div class="header-top">
        <div class="header-title">
          <span class="n8n-logo">⚡</span>
          <span class="title-text">n8n MCP</span>
        </div>
        <div class="connection-block">
          <span class="status-dot" :style="{ backgroundColor: statusColor }"></span>
          <span class="status-label">{{ statusText }}</span>
        </div>
      </div>

      <!-- Server URL -->
      <div class="server-row">
        <input
          v-model="serverUrl"
          class="server-input"
          placeholder="http://localhost:3006"
          :disabled="connectionStatus === 'connected'"
        />
        <button
          class="connect-btn"
          :class="{
            'btn-connected': connectionStatus === 'connected',
            'btn-connecting': isConnecting,
          }"
          @click="toggleConnection"
          :disabled="isConnecting"
        >
          {{ connectionStatus === "connected" ? "Disconnect" : isConnecting ? "..." : "Connect" }}
        </button>
      </div>

      <!-- Tabs -->
      <div class="tab-bar">
        <button
          v-for="tab in [
            { key: 'quick', label: '⚡ Quick', count: 0 },
            { key: 'tools', label: '🔧 Tools', count: tools.length },
            { key: 'log', label: '📊 Log', count: executions.length },
          ]"
          :key="tab.key"
          class="tab-btn"
          :class="{ active: activeTab === tab.key }"
          @click="activeTab = tab.key as any"
        >
          {{ tab.label }}
          <span v-if="tab.count" class="tab-badge">{{ tab.count }}</span>
        </button>
      </div>
    </div>

    <!-- Content -->
    <div class="panel-content">
      <!-- Quick Actions -->
      <div v-if="activeTab === 'quick'" class="quick-actions">
        <div v-if="connectionStatus !== 'connected'" class="empty-state">
          <span class="empty-icon">🔌</span>
          <p class="empty-text">Connect to MCP server to get started</p>
          <p class="empty-hint">
            Run <code>start-mcp.bat</code> first, then click Connect
          </p>
        </div>
        <template v-else>
          <div class="quick-grid">
            <button
              v-for="action in quickActions"
              :key="action.tool"
              class="quick-card"
              @click="runQuickAction(action)"
            >
              <span class="quick-icon">{{ action.icon }}</span>
              <span class="quick-label">{{ action.label }}</span>
              <span class="quick-tool">{{ action.tool }}</span>
            </button>
          </div>

          <!-- Stats -->
          <div class="stats-bar">
            <div class="stat">
              <span class="stat-value">{{ tools.length }}</span>
              <span class="stat-label">Tools</span>
            </div>
            <div class="stat">
              <span class="stat-value">{{ executions.length }}</span>
              <span class="stat-label">Executions</span>
            </div>
            <div class="stat">
              <span class="stat-value">{{ executions.filter(e => e.status === 'success').length }}</span>
              <span class="stat-label">Success</span>
            </div>
            <div class="stat">
              <span class="stat-value">{{ executions.filter(e => e.status === 'error').length }}</span>
              <span class="stat-label">Errors</span>
            </div>
          </div>
        </template>
      </div>

      <!-- Tools List -->
      <div v-if="activeTab === 'tools'" class="tools-tab">
        <div v-if="tools.length" class="search-box">
          <input
            v-model="searchQuery"
            class="search-input"
            placeholder="Search tools..."
          />
        </div>
        <div v-if="filteredTools.length" class="tools-list">
          <ToolCard
            v-for="tool in filteredTools"
            :key="tool.name"
            :tool="tool"
            @execute="handleToolExecute"
          />
        </div>
        <div v-else-if="connectionStatus !== 'connected'" class="empty-state">
          <span class="empty-icon">🔧</span>
          <p class="empty-text">No tools available</p>
          <p class="empty-hint">Connect to MCP server first</p>
        </div>
        <div v-else class="empty-state">
          <span class="empty-icon">🔍</span>
          <p class="empty-text">No tools match "{{ searchQuery }}"</p>
        </div>
      </div>

      <!-- Execution Log -->
      <div v-if="activeTab === 'log'" class="log-tab">
        <ExecutionLog
          :executions="executions"
          @clear="clearLog"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.n8n-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--color-background, #0f0f0f);
  color: var(--color-text, #e5e5e5);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.panel-header {
  padding: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  background: rgba(255, 255, 255, 0.02);
  flex-shrink: 0;
}

.header-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 6px;
}

.n8n-logo {
  font-size: 18px;
}

.title-text {
  font-size: 15px;
  font-weight: 700;
  background: linear-gradient(135deg, #ff6d5a 0%, #ff9a44 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.connection-block {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
}

.status-dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  transition: background-color 0.3s;
  box-shadow: 0 0 6px currentColor;
}

.server-row {
  display: flex;
  gap: 6px;
  margin-bottom: 10px;
}

.server-input {
  flex: 1;
  padding: 6px 10px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 6px;
  color: inherit;
  font-size: 12px;
  outline: none;
  transition: border-color 0.2s;
}

.server-input:focus {
  border-color: rgba(255, 109, 90, 0.4);
}

.server-input:disabled {
  opacity: 0.5;
}

.connect-btn {
  padding: 6px 14px;
  background: linear-gradient(135deg, #ff6d5a, #ff9a44);
  border: none;
  border-radius: 6px;
  color: white;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}

.connect-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.connect-btn:active {
  transform: scale(0.97);
}

.connect-btn.btn-connected {
  background: rgba(255, 255, 255, 0.08);
  color: rgba(255, 255, 255, 0.6);
}

.connect-btn.btn-connected:hover {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.connect-btn.btn-connecting {
  opacity: 0.6;
  cursor: wait;
}

.tab-bar {
  display: flex;
  gap: 2px;
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  padding: 2px;
}

.tab-btn {
  flex: 1;
  padding: 6px 8px;
  background: transparent;
  border: none;
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.4);
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.tab-btn:hover {
  color: rgba(255, 255, 255, 0.7);
  background: rgba(255, 255, 255, 0.04);
}

.tab-btn.active {
  background: rgba(255, 109, 90, 0.15);
  color: #ff8a65;
  font-weight: 600;
}

.tab-badge {
  font-size: 10px;
  background: rgba(255, 255, 255, 0.1);
  padding: 1px 5px;
  border-radius: 10px;
  min-width: 16px;
  text-align: center;
}

.tab-btn.active .tab-badge {
  background: rgba(255, 109, 90, 0.25);
}

.panel-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

/* Scrollbar */
.panel-content::-webkit-scrollbar {
  width: 4px;
}
.panel-content::-webkit-scrollbar-track {
  background: transparent;
}
.panel-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

/* Quick Actions */
.quick-actions {
  padding: 12px;
}

.quick-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.quick-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 14px 8px;
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.06);
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s;
  color: inherit;
}

.quick-card:hover {
  background: rgba(255, 109, 90, 0.08);
  border-color: rgba(255, 109, 90, 0.2);
  transform: translateY(-1px);
}

.quick-card:active {
  transform: scale(0.97);
}

.quick-icon {
  font-size: 22px;
}

.quick-label {
  font-size: 12px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.8);
}

.quick-tool {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.3);
  font-family: monospace;
}

.stats-bar {
  display: flex;
  gap: 4px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 10px;
  padding: 12px;
  border: 1px solid rgba(255, 255, 255, 0.04);
}

.stat {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.stat-value {
  font-size: 18px;
  font-weight: 700;
  background: linear-gradient(135deg, #ff6d5a, #ff9a44);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.stat-label {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.35);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* Tools Tab */
.tools-tab {
  padding: 12px;
}

.search-box {
  margin-bottom: 10px;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 8px;
  color: inherit;
  font-size: 13px;
  outline: none;
  box-sizing: border-box;
}

.search-input:focus {
  border-color: rgba(255, 109, 90, 0.4);
}

.tools-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

/* Log Tab */
.log-tab {
  height: 100%;
}

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

.empty-icon {
  font-size: 40px;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.5);
  margin: 0 0 6px;
}

.empty-hint {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.3);
  margin: 0;
}

.empty-hint code {
  background: rgba(255, 109, 90, 0.15);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  color: #ff8a65;
}

/* Dark/Light mode support */
@media (prefers-color-scheme: light) {
  .n8n-panel {
    background: #fafafa;
    color: #1a1a1a;
  }

  .panel-header {
    border-bottom-color: rgba(0, 0, 0, 0.08);
    background: rgba(0, 0, 0, 0.02);
  }

  .server-input {
    background: rgba(0, 0, 0, 0.04);
    border-color: rgba(0, 0, 0, 0.1);
    color: #1a1a1a;
  }

  .tab-bar {
    background: rgba(0, 0, 0, 0.03);
  }

  .tab-btn {
    color: rgba(0, 0, 0, 0.4);
  }

  .tab-btn:hover {
    color: rgba(0, 0, 0, 0.7);
    background: rgba(0, 0, 0, 0.04);
  }

  .quick-card {
    background: rgba(0, 0, 0, 0.02);
    border-color: rgba(0, 0, 0, 0.08);
  }

  .quick-label {
    color: rgba(0, 0, 0, 0.8);
  }

  .quick-tool {
    color: rgba(0, 0, 0, 0.4);
  }

  .connection-block {
    color: rgba(0, 0, 0, 0.5);
  }

  .search-input {
    background: rgba(0, 0, 0, 0.04);
    border-color: rgba(0, 0, 0, 0.1);
    color: #1a1a1a;
  }

  .empty-text {
    color: rgba(0, 0, 0, 0.5);
  }

  .empty-hint {
    color: rgba(0, 0, 0, 0.35);
  }
}
</style>
