<script setup lang="ts">
const vault = useVault()

const credentials = ref<any[]>([])
const sshKeys = ref<any[]>([])
const loading = ref(true)
const showForm = ref(false)
const editingCred = ref<any>(null)
const deletingId = ref<number | null>(null)

async function load() {
  loading.value = true
  try {
    const [creds, keys] = await Promise.all([
      vault.listCredentials() as Promise<any[]>,
      vault.listKeys() as Promise<any[]>,
    ])
    credentials.value = creds
    sshKeys.value = keys
  } finally {
    loading.value = false
  }
}

function openCreate() {
  editingCred.value = null
  showForm.value = true
}

function openEdit(cred: any) {
  editingCred.value = cred
  showForm.value = true
}

async function confirmDelete(cred: any) {
  if (!confirm(`Delete credential "${cred.name}"?`)) return
  deletingId.value = cred.id
  try {
    await vault.deleteCredential(cred.id)
    await load()
  } finally {
    deletingId.value = null
  }
}

onMounted(load)
</script>

<template>
  <div class="max-w-4xl mx-auto p-6">
    <div class="flex items-center justify-between mb-6">
      <div class="flex items-center gap-3">
        <NuxtLink to="/vault" class="text-gray-500 hover:text-gray-300 text-sm">Vault</NuxtLink>
        <span class="text-gray-700">/</span>
        <h2 class="text-xl font-bold text-white">Credentials</h2>
      </div>
      <button @click="openCreate"
        class="px-3 py-1.5 bg-wraith-600 hover:bg-wraith-700 text-white text-sm rounded">
        New Credential
      </button>
    </div>

    <div v-if="loading" class="text-gray-500 text-sm">Loading...</div>

    <div v-else-if="credentials.length === 0" class="text-center py-12 text-gray-600">
      <p>No credentials yet.</p>
      <button @click="openCreate" class="mt-3 text-wraith-400 hover:text-wraith-300 text-sm">
        Create your first credential
      </button>
    </div>

    <div v-else class="bg-gray-800 rounded-lg border border-gray-700 overflow-hidden">
      <table class="w-full text-sm">
        <thead>
          <tr class="border-b border-gray-700 text-gray-400">
            <th class="text-left px-4 py-3 font-medium">Name</th>
            <th class="text-left px-4 py-3 font-medium">Username</th>
            <th class="text-left px-4 py-3 font-medium">Type</th>
            <th class="text-left px-4 py-3 font-medium">Associated Hosts</th>
            <th class="px-4 py-3"></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="cred in credentials" :key="cred.id"
            class="border-b border-gray-700/50 hover:bg-gray-700/30">
            <td class="px-4 py-3 text-white font-medium">{{ cred.name }}</td>
            <td class="px-4 py-3 text-gray-300">{{ cred.username || '—' }}</td>
            <td class="px-4 py-3">
              <span :class="[
                'px-2 py-0.5 rounded text-xs font-medium',
                cred.type === 'password' ? 'bg-blue-900/50 text-blue-300' : 'bg-purple-900/50 text-purple-300'
              ]">
                {{ cred.type === 'ssh_key' ? 'SSH Key' : 'Password' }}
              </span>
            </td>
            <td class="px-4 py-3 text-gray-400 text-xs">
              {{ cred.hosts?.length ? cred.hosts.map((h: any) => h.name).join(', ') : '—' }}
            </td>
            <td class="px-4 py-3 text-right flex items-center justify-end gap-3">
              <button @click="openEdit(cred)" class="text-xs text-gray-400 hover:text-white">Edit</button>
              <button @click="confirmDelete(cred)"
                :disabled="deletingId === cred.id"
                class="text-xs text-red-400 hover:text-red-300 disabled:opacity-50">
                {{ deletingId === cred.id ? 'Deleting...' : 'Delete' }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <CredentialForm
      v-model:visible="showForm"
      :credential="editingCred"
      :ssh-keys="sshKeys"
      @saved="load"
    />
  </div>
</template>
