<script setup lang="ts">
import { ref, onMounted } from "vue"

const n8nApiUrl = ref("")
const n8nApiKey = ref("")
const mcpAuthToken = ref("")
const proxyUrl = ref("http://localhost:3000")
const saving = ref(false)
const saved = ref(false)
const showKey = ref(false)
const connectionStatus = ref<"idle" | "testing" | "ok" | "error">("idle")
const connectionError = ref("")

const STORAGE_KEY = "mcp_n8n_config"

onMounted(async () => {
  const data = await chrome.storage.local.get(STORAGE_KEY)
  if (data[STORAGE_KEY]) {
    n8nApiUrl.value = data[STORAGE_KEY].n8nApiUrl || ""
    n8nApiKey.value = data[STORAGE_KEY].n8nApiKey || ""
    mcpAuthToken.value = data[STORAGE_KEY].mcpAuthToken || ""
    proxyUrl.value = data[STORAGE_KEY].proxyUrl || "http://localhost:3000"
  }
})

async function save() {
  saving.value = true
  saved.value = false
  try {
    await chrome.storage.local.set({
      [STORAGE_KEY]: {
        n8nApiUrl: n8nApiUrl.value.replace(/\/+$/, ""),
        n8nApiKey: n8nApiKey.value,
        mcpAuthToken: mcpAuthToken.value,
        proxyUrl: proxyUrl.value.replace(/\/+$/, ""),
      },
    })
    saved.value = true
    setTimeout(() => (saved.value = false), 2500)
  } finally {
    saving.value = false
  }
}

async function testConnection() {
  connectionStatus.value = "testing"
  connectionError.value = ""
  const url = proxyUrl.value.replace(/\/+$/, "")
  try {
    const headers: Record<string, string> = {}
    if (mcpAuthToken.value) {
      headers["Authorization"] = `Bearer ${mcpAuthToken.value}`
    }
    const res = await fetch(`${url}/health`, {
      method: "GET",
      headers,
      signal: AbortSignal.timeout(5000),
    })
    if (res.ok) {
      connectionStatus.value = "ok"
    } else {
      connectionStatus.value = "error"
      connectionError.value = `HTTP ${res.status}`
    }
  } catch (e: any) {
    connectionStatus.value = "error"
    connectionError.value = e?.message || "Connection failed"
  }
}

const statusDot: Record<string, string> = {
  idle: "bg-zinc-500",
  testing: "bg-amber-400 animate-pulse",
  ok: "bg-emerald-500",
  error: "bg-red-500",
}

const statusText: Record<string, string> = {
  idle: "Chưa kiểm tra",
  testing: "Đang kiểm tra...",
  ok: "Đã kết nối ✓",
  error: "Lỗi kết nối",
}
</script>

<template>
  <div class="mcp-settings">
    <!-- Header -->
    <div class="settings-header">
      <div class="header-icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z" />
          <path d="M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z" />
          <path d="M12 2v2" /><path d="M12 22v-2" />
          <path d="m17 20.66-1-1.73" /><path d="M11 10.27 7 3.34" />
          <path d="m20.66 17-1.73-1" /><path d="m3.34 7 1.73 1" />
          <path d="M14 12h8" /><path d="M2 12h2" />
          <path d="m20.66 7-1.73 1" /><path d="m3.34 17 1.73-1" />
          <path d="m17 3.34-1 1.73" /><path d="m11 13.73-4 6.93" />
        </svg>
      </div>
      <div>
        <h3 class="header-title">n8n MCP Configuration</h3>
        <p class="header-desc">Kết nối extension với n8n instance của bạn</p>
      </div>
    </div>

    <!-- Connection Status -->
    <div class="status-bar">
      <div class="status-indicator">
        <span :class="['status-dot', statusDot[connectionStatus]]"></span>
        <span class="status-label">{{ statusText[connectionStatus] }}</span>
      </div>
      <button class="btn-test" @click="testConnection" :disabled="connectionStatus === 'testing'">
        Test
      </button>
    </div>

    <p v-if="connectionError" class="error-text">{{ connectionError }}</p>

    <!-- Form -->
    <div class="form-group">
      <label class="form-label">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
          <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
        </svg>
        n8n Instance URL
      </label>
      <input v-model="n8nApiUrl" class="form-input" type="url"
        placeholder="http://localhost:5678" spellcheck="false" />
      <span class="form-hint">URL instance n8n của bạn (không cần /api/v1)</span>
    </div>

    <div class="form-group">
      <label class="form-label">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <rect width="18" height="11" x="3" y="11" rx="2" ry="2"/>
          <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
        </svg>
        n8n API Key
      </label>
      <div class="input-group">
        <input v-model="n8nApiKey" class="form-input pr-10"
          :type="showKey ? 'text' : 'password'"
          placeholder="n8n-api-key-xxxx" spellcheck="false" />
        <button class="btn-toggle-key" @click="showKey = !showKey" :title="showKey ? 'Ẩn' : 'Hiện'">
          <svg v-if="!showKey" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/>
            <circle cx="12" cy="12" r="3"/>
          </svg>
          <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/>
            <path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/>
            <path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/>
            <line x1="2" x2="22" y1="2" y2="22"/>
          </svg>
        </button>
      </div>
      <span class="form-hint">Settings → API → Create API Key trong n8n</span>
    </div>

    <div class="form-group">
      <label class="form-label">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <rect width="20" height="8" x="2" y="2" rx="2" ry="2"/>
          <rect width="20" height="8" x="2" y="14" rx="2" ry="2"/>
          <line x1="6" x2="6.01" y1="6" y2="6"/>
          <line x1="6" x2="6.01" y1="18" y2="18"/>
        </svg>
        MCP Server URL
      </label>
      <input v-model="proxyUrl" class="form-input" type="url"
        placeholder="http://localhost:3000" spellcheck="false" />
      <span class="form-hint">URL của n8n-mcp server (Ex: http://vps-ip:3000)</span>
    </div>

    <div class="form-group">
      <label class="form-label">
        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"></path>
        </svg>
        MCP Auth Token
      </label>
      <input v-model="mcpAuthToken" class="form-input" type="password"
        placeholder="Nhập nếu server yêu cầu" spellcheck="false" />
      <span class="form-hint">Token bảo vệ n8n-mcp của bạn (tuỳ chọn)</span>
    </div>

    <!-- Actions -->
    <div class="form-actions">
      <button class="btn-save" @click="save" :disabled="saving || !n8nApiUrl || !n8nApiKey">
        <template v-if="saving">Đang lưu...</template>
        <template v-else-if="saved">Đã lưu ✓</template>
        <template v-else>Lưu cấu hình</template>
      </button>
    </div>

    <!-- Info Card -->
    <div class="info-card">
      <p class="info-title">📋 Hướng dẫn nhanh</p>
      <ol class="info-list">
        <li>Mở n8n instance → <strong>Settings → API</strong></li>
        <li>Click <strong>"Create API Key"</strong> và copy key</li>
        <li>Chạy <code>npx n8n-mcp</code> trên máy tính/server của bạn</li>
        <li>Nhập các thông tin trên, bấm <strong>Lưu cấu hình</strong></li>
        <li>Bấm <strong>Test</strong> để kiểm tra kết nối</li>
      </ol>
    </div>
  </div>
</template>

<style scoped>
.mcp-settings {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: var(--color-text, #e4e4e7);
}

.settings-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(255,255,255,0.08);
}

.header-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: linear-gradient(135deg, #ff6d5a 0%, #ee3f3f 100%);
  color: white;
  flex-shrink: 0;
}

.header-title {
  font-size: 15px;
  font-weight: 600;
  margin: 0;
  color: var(--color-heading, #fafafa);
}

.header-desc {
  font-size: 12px;
  margin: 2px 0 0;
  opacity: 0.6;
}

/* Status bar */
.status-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border-radius: 8px;
  background: rgba(255,255,255,0.04);
  border: 1px solid rgba(255,255,255,0.06);
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-label {
  font-size: 12px;
  opacity: 0.8;
}

.btn-test {
  font-size: 11px;
  padding: 4px 12px;
  border: 1px solid rgba(255,255,255,0.12);
  border-radius: 6px;
  background: rgba(255,255,255,0.06);
  color: inherit;
  cursor: pointer;
  transition: all 0.15s;
}
.btn-test:hover { background: rgba(255,255,255,0.1); }
.btn-test:disabled { opacity: 0.4; cursor: not-allowed; }

.error-text {
  font-size: 12px;
  color: #ef4444;
  margin: -8px 0 0;
  padding-left: 4px;
}

/* Form */
.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 500;
  opacity: 0.8;
}

.form-input {
  width: 100%;
  padding: 8px 12px;
  font-size: 13px;
  border: 1px solid rgba(255,255,255,0.1);
  border-radius: 8px;
  background: rgba(255,255,255,0.04);
  color: inherit;
  outline: none;
  transition: border-color 0.15s;
  box-sizing: border-box;
  font-family: 'SF Mono', Monaco, Consolas, monospace;
}
.form-input:focus {
  border-color: #ff6d5a;
}
.form-input::placeholder {
  opacity: 0.35;
}

.pr-10 { padding-right: 38px; }

.input-group {
  position: relative;
}

.btn-toggle-key {
  position: absolute;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  padding: 6px;
  color: inherit;
  opacity: 0.5;
  cursor: pointer;
}
.btn-toggle-key:hover { opacity: 0.9; }

.form-hint {
  font-size: 11px;
  opacity: 0.4;
  padding-left: 2px;
}

/* Actions */
.form-actions {
  padding-top: 4px;
}

.btn-save {
  width: 100%;
  padding: 10px;
  font-size: 13px;
  font-weight: 600;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #ff6d5a 0%, #ee3f3f 100%);
  color: white;
  cursor: pointer;
  transition: all 0.2s;
}
.btn-save:hover { opacity: 0.9; transform: translateY(-1px); }
.btn-save:active { transform: translateY(0); }
.btn-save:disabled { opacity: 0.4; cursor: not-allowed; transform: none; }

/* Info */
.info-card {
  padding: 12px 14px;
  border-radius: 8px;
  background: rgba(255,255,255,0.03);
  border: 1px solid rgba(255,255,255,0.06);
}

.info-title {
  font-size: 12px;
  font-weight: 600;
  margin: 0 0 8px;
}

.info-list {
  font-size: 11px;
  margin: 0;
  padding-left: 18px;
  line-height: 1.7;
  opacity: 0.65;
}

.info-list code {
  padding: 1px 5px;
  border-radius: 4px;
  background: rgba(255,255,255,0.08);
  font-family: 'SF Mono', Monaco, Consolas, monospace;
  font-size: 10px;
}
</style>
