<script setup lang="ts">
import { ref } from 'vue'
import { useUiStore } from '../../stores/ui'
import { configApi } from '../../services/configApi'
import type { DiscoveredConnection } from '../../types'

const ui = useUiStore()

// Discovery
const discovered = ref<DiscoveredConnection[]>([])
const scanning = ref(false)
const selectedDiscovered = ref<DiscoveredConnection | null>(null)
const credForm = ref({ username: '', password: '' })

// Manual
const showManual = ref(false)
const manualForm = ref({ name: '', db_type: 'sqlserver', source_system: 'sap_ecc', connection_string: '' })

// Existing
const connections = ref<any[]>([])
const saving = ref(false)

async function fetchConnections() {
  const { data } = await configApi.listConnections()
  connections.value = data
}
fetchConnections()

async function autoDiscover() {
  scanning.value = true
  try {
    const { data } = await configApi.discoverConnections()
    discovered.value = data
    if (data.length === 0) {
      ui.showToast('No connections found. Try adding one manually.', 'info')
      showManual.value = true
    }
  } catch {
    ui.showToast('Auto-discovery failed', 'error')
  } finally {
    scanning.value = false
  }
}

function selectDiscovered(conn: DiscoveredConnection) {
  selectedDiscovered.value = conn
  credForm.value = { username: '', password: '' }
}

async function addFromDiscovered() {
  if (!selectedDiscovered.value) return
  saving.value = true
  const dc = selectedDiscovered.value
  try {
    await configApi.createConnection({
      name: dc.name,
      db_type: dc.db_type,
      source_system: dc.source_system || undefined,
      connection_string_template: dc.connection_string_template,
      username: credForm.value.username,
      password: credForm.value.password,
    })
    ui.showToast('Connection added', 'success')
    selectedDiscovered.value = null
    await fetchConnections()
  } catch (e: any) {
    ui.showToast(e.response?.data?.detail || 'Failed', 'error')
  } finally {
    saving.value = false
  }
}

async function addManual() {
  saving.value = true
  try {
    await configApi.createConnection(manualForm.value)
    ui.showToast('Connection added', 'success')
    manualForm.value = { name: '', db_type: 'sqlserver', source_system: 'sap_ecc', connection_string: '' }
    showManual.value = false
    await fetchConnections()
  } catch (e: any) {
    ui.showToast(e.response?.data?.detail || 'Failed', 'error')
  } finally {
    saving.value = false
  }
}

function dbTypeLabel(t: string) {
  const m: Record<string, string> = {
    sqlserver: 'SQL Server', sybase: 'SAP Sybase ASE', hana: 'SAP HANA',
    postgresql: 'PostgreSQL', mysql: 'MySQL / MariaDB', oracle: 'Oracle', db2: 'IBM Db2',
  }
  return m[t] || t
}
</script>

<template>
  <div>
    <h2 class="text-lg font-semibold mb-2">Connect Your Databases</h2>
    <p class="text-dark-400 text-sm mb-4">
      V3Q.AI can auto-discover your existing database connections from ODBC, DBeaver, and SSMS.
    </p>

    <!-- Auto-discover button -->
    <div class="flex gap-2 mb-4">
      <button @click="autoDiscover" :disabled="scanning" class="btn-primary text-sm">
        {{ scanning ? 'Scanning...' : 'Auto-Discover Connections' }}
      </button>
      <button @click="showManual = !showManual" class="btn-secondary text-sm">
        {{ showManual ? 'Hide Manual' : 'Enter Manually' }}
      </button>
    </div>

    <!-- Discovered connections -->
    <div v-if="discovered.length > 0" class="mb-4">
      <p class="text-xs text-dark-500 mb-2">Select a connection to add it:</p>
      <div class="grid grid-cols-1 gap-2">
        <button
          v-for="(dc, idx) in discovered"
          :key="idx"
          @click="selectDiscovered(dc)"
          :class="[
            'text-left p-3 rounded-lg border transition-colors',
            selectedDiscovered === dc
              ? 'border-primary-500 bg-primary-500/10'
              : 'border-dark-600 bg-dark-800 hover:border-dark-400'
          ]"
        >
          <div class="flex items-center justify-between">
            <div>
              <span class="font-medium text-sm">{{ dc.name }}</span>
              <span class="ml-2 text-xs text-dark-500">{{ dbTypeLabel(dc.db_type) }}</span>
            </div>
            <span class="text-[10px] bg-dark-700 px-2 py-0.5 rounded text-dark-400">{{ dc.source }}</span>
          </div>
          <div class="text-xs text-dark-500 mt-1">
            <span v-if="dc.server">{{ dc.server }}</span>
            <span v-if="dc.database"> &middot; {{ dc.database }}</span>
          </div>
        </button>
      </div>
    </div>

    <!-- Credentials for selected -->
    <div v-if="selectedDiscovered" class="bg-dark-800 border border-primary-500/30 rounded-lg p-4 mb-4">
      <p class="text-sm font-medium mb-1">{{ selectedDiscovered.name }}</p>
      <p class="text-xs text-dark-500 mb-3">Enter credentials to connect:</p>
      <div class="grid grid-cols-2 gap-3 mb-3">
        <input v-model="credForm.username" placeholder="Username" class="input-field" autocomplete="off" />
        <input v-model="credForm.password" type="password" placeholder="Password" class="input-field" autocomplete="off" />
      </div>
      <div class="flex gap-2">
        <button @click="addFromDiscovered" :disabled="saving" class="btn-primary text-sm">
          {{ saving ? 'Adding...' : 'Add Connection' }}
        </button>
        <button @click="selectedDiscovered = null" class="btn-secondary text-sm">Cancel</button>
      </div>
    </div>

    <!-- Manual form -->
    <div v-if="showManual" class="space-y-3 mb-4">
      <input v-model="manualForm.name" placeholder="Connection name (e.g., SAP ECC Production)" class="input-field" />
      <div class="grid grid-cols-2 gap-3">
        <select v-model="manualForm.db_type" class="input-field">
          <option value="sqlserver">SQL Server</option>
          <option value="sybase">SAP Sybase ASE</option>
          <option value="hana">SAP HANA</option>
          <option value="postgresql">PostgreSQL</option>
          <option value="mysql">MySQL / MariaDB</option>
          <option value="oracle">Oracle</option>
          <option value="db2">IBM Db2</option>
        </select>
        <select v-model="manualForm.source_system" class="input-field">
          <option value="sap_ecc">SAP ECC</option>
          <option value="sap_b1">SAP Business One</option>
          <option value="hubspot">HubSpot</option>
          <option value="infor">Infor</option>
          <option value="other">Other</option>
        </select>
      </div>
      <input v-model="manualForm.connection_string" placeholder="Connection string" class="input-field font-mono text-xs" />
      <button @click="addManual" :disabled="saving" class="btn-primary text-sm">
        {{ saving ? 'Saving...' : 'Add Connection' }}
      </button>
    </div>

    <!-- Existing connections -->
    <div v-if="connections.length" class="space-y-2">
      <p class="text-xs text-dark-500 mb-1">Added connections:</p>
      <div v-for="c in connections" :key="c.id" class="flex items-center justify-between p-2 bg-dark-900 rounded text-sm">
        <span>{{ c.name }} <span class="text-dark-500">({{ dbTypeLabel(c.db_type) }})</span></span>
        <span class="text-green-400 text-xs">Ready</span>
      </div>
    </div>
    <p v-else-if="!discovered.length && !showManual" class="text-dark-500 text-sm">
      Click "Auto-Discover" to find existing database connections, or "Enter Manually" to type a connection string.
    </p>
  </div>
</template>
