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

const store = useAgentsStore()
const showAddModal = ref(false)
const editingServer = ref<string | null>(null)

const newServer = ref<McpServerEntry>({
  name: '',
  type: 'stdio',
  command: '',
  args: [],
  url: '',
  env: {},
  enabled: true
})

const argsText = ref('')
const envText = ref('')

function resetForm() {
  newServer.value = { name: '', type: 'stdio', command: '', args: [], url: '', env: {}, enabled: true }
  argsText.value = ''
  envText.value = ''
  editingServer.value = null
}

function openAddModal() {
  resetForm()
  showAddModal.value = true
}

function openEditModal(server: McpServerEntry) {
  newServer.value = { ...server, args: [...(server.args || [])], env: { ...(server.env || {}) } }
  argsText.value = (server.args || []).join('\n')
  envText.value = Object.entries(server.env || {}).map(([k, v]) => `${k}=${v}`).join('\n')
  editingServer.value = server.name
  showAddModal.value = true
}

function saveServer() {
  if (!newServer.value.name.trim()) return

  // Parse args from text
  newServer.value.args = argsText.value.split('\n').map(s => s.trim()).filter(Boolean)

  // Parse env from text
  const env: Record<string, string> = {}
  for (const line of envText.value.split('\n')) {
    const eq = line.indexOf('=')
    if (eq > 0) {
      env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim()
    }
  }
  newServer.value.env = env

  if (editingServer.value) {
    // Update existing
    const idx = store.mcpServers.findIndex(s => s.name === editingServer.value)
    if (idx >= 0) {
      store.mcpServers[idx] = { ...newServer.value }
    }
  } else {
    store.addMcpServer({ ...newServer.value })
  }

  showAddModal.value = false
  resetForm()
}

function deleteServer(name: string) {
  store.removeMcpServer(name)
}
</script>

<template>
  <div class="mcp-manager">
    <!-- Header -->
    <div class="mcp-header">
      <div class="mcp-header-left">
        <h3>MCP Servers</h3>
        <span class="mcp-count">{{ store.mcpServers.length }} servers</span>
        <span class="mcp-path">.mcp.json</span>
      </div>
      <div class="mcp-header-right">
        <button class="btn btn-secondary" @click="openAddModal">+ Add Server</button>
        <button
          class="btn btn-primary"
          :disabled="store.saving"
          @click="store.saveMcpServers()"
        >{{ store.saving ? 'Saving...' : 'Save' }}</button>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="store.mcpsLoading" class="mcp-loading">Loading MCP servers...</div>

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

    <!-- Server cards -->
    <div v-if="!store.mcpsLoading" class="mcp-scroll">
      <div class="server-grid">
        <div v-for="server in store.mcpServers" :key="server.name" class="server-card">
          <div class="server-card-header">
            <div class="server-info">
              <span class="server-name">{{ server.name }}</span>
              <span class="server-type-badge" :class="server.type">{{ server.type }}</span>
            </div>
            <div class="server-actions">
              <button
                class="toggle-btn"
                :class="{ enabled: server.enabled }"
                @click="store.toggleMcpServer(server.name)"
                :title="server.enabled ? 'Disable' : 'Enable'"
              >
                <span class="toggle-dot"></span>
              </button>
            </div>
          </div>

          <div class="server-card-body">
            <div v-if="server.command" class="server-detail">
              <span class="detail-label">Command</span>
              <code>{{ server.command }}</code>
            </div>
            <div v-if="server.args?.length" class="server-detail">
              <span class="detail-label">Args</span>
              <code>{{ server.args.join(' ') }}</code>
            </div>
            <div v-if="server.url" class="server-detail">
              <span class="detail-label">URL</span>
              <code>{{ server.url }}</code>
            </div>
            <div v-if="server.env && Object.keys(server.env).length" class="server-detail">
              <span class="detail-label">Env</span>
              <span class="env-count">{{ Object.keys(server.env).length }} vars</span>
            </div>
          </div>

          <div class="server-card-footer">
            <button class="btn-link" @click="openEditModal(server)">Edit</button>
            <button class="btn-link danger" @click="deleteServer(server.name)">Delete</button>
          </div>
        </div>
      </div>

      <div v-if="!store.mcpServers.length" class="mcp-empty">
        <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
        <p>No MCP servers configured</p>
        <span>Add a server to get started</span>
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal" class="modal-overlay" @click.self="showAddModal = false">
      <div class="modal">
        <div class="modal-header">
          <h4>{{ editingServer ? 'Edit Server' : 'Add MCP Server' }}</h4>
          <button class="modal-close" @click="showAddModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Name</label>
            <input type="text" v-model="newServer.name" placeholder="my-server" :disabled="!!editingServer" />
          </div>
          <div class="form-group">
            <label>Type</label>
            <select v-model="newServer.type">
              <option value="stdio">stdio</option>
              <option value="sse">sse</option>
              <option value="streamable-http">streamable-http</option>
            </select>
          </div>
          <div v-if="newServer.type === 'stdio'" class="form-group">
            <label>Command</label>
            <input type="text" v-model="newServer.command" placeholder="npx" />
          </div>
          <div v-if="newServer.type === 'stdio'" class="form-group">
            <label>Args (one per line)</label>
            <textarea v-model="argsText" placeholder="arg1&#10;arg2" rows="3"></textarea>
          </div>
          <div v-if="newServer.type !== 'stdio'" class="form-group">
            <label>URL</label>
            <input type="text" v-model="newServer.url" placeholder="http://localhost:3000" />
          </div>
          <div class="form-group">
            <label>Environment (KEY=value, one per line)</label>
            <textarea v-model="envText" placeholder="API_KEY=xxx" rows="2"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showAddModal = false">Cancel</button>
          <button class="btn btn-primary" @click="saveServer">{{ editingServer ? 'Update' : 'Add' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

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

.mcp-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;
}

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

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

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

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

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

.mcp-loading,
.mcp-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;
}

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

.mcp-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);
}

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

/* Server grid */
.server-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 0.75rem;
}

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

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

.server-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.server-name {
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-primary);
}

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

.server-type-badge.stdio { background: rgba(99, 102, 241, 0.12); color: #6366f1; }
.server-type-badge.sse { background: rgba(245, 158, 11, 0.12); color: #f59e0b; }
.server-type-badge.streamable-http { background: rgba(16, 185, 129, 0.12); color: #10b981; }

.server-actions {
  display: flex;
  gap: 0.375rem;
}

.toggle-btn {
  width: 36px;
  height: 20px;
  border-radius: 10px;
  border: none;
  background: var(--bg-hover);
  cursor: pointer;
  position: relative;
  transition: background 0.2s;
}

.toggle-btn.enabled {
  background: #22c55e;
}

.toggle-dot {
  position: absolute;
  top: 2px;
  left: 2px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: white;
  transition: transform 0.2s;
}

.toggle-btn.enabled .toggle-dot {
  transform: translateX(16px);
}

.server-card-body {
  padding: 0.625rem 0.75rem;
}

.server-detail {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
  padding: 0.1875rem 0;
}

.detail-label {
  font-size: 0.625rem;
  font-weight: 600;
  color: var(--text-muted);
  text-transform: uppercase;
  min-width: 60px;
  flex-shrink: 0;
}

.server-detail code {
  font-size: 0.6875rem;
  color: var(--text-secondary);
  font-family: 'Consolas', monospace;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

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

.server-card-footer {
  display: flex;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  border-top: 1px solid var(--border-color);
}

.btn-link {
  background: none;
  border: none;
  color: #6366f1;
  font-size: 0.6875rem;
  font-weight: 500;
  cursor: pointer;
  padding: 0;
}

.btn-link:hover {
  text-decoration: underline;
}

.btn-link.danger {
  color: #ef4444;
}

/* Modal */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.modal {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  width: 480px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

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

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

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

.modal-body {
  padding: 1rem;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 0.75rem;
}

.form-group label {
  display: block;
  font-size: 0.6875rem;
  font-weight: 600;
  color: var(--text-secondary);
  margin-bottom: 0.25rem;
  text-transform: uppercase;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.375rem 0.5rem;
  font-size: 0.8125rem;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--bg-secondary);
  color: var(--text-primary);
  outline: none;
  font-family: 'Consolas', monospace;
  box-sizing: border-box;
}

.form-group textarea {
  resize: vertical;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: #6366f1;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border-top: 1px solid var(--border-color);
}

/* Buttons */
.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-secondary {
  background: var(--bg-secondary);
  color: var(--text-secondary);
}

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

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

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