<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)

// Inline credential form state
const credForm = ref({
  name: '',
  type: 'password' as 'password' | 'ssh_key',
  username: '',
  password: '',
  sshKeyId: null as number | null,
  domain: '',
})
const credSaving = ref(false)
const credError = ref('')

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
  credForm.value = { name: '', type: 'password', username: '', password: '', sshKeyId: null, domain: '' }
  credError.value = ''
  showForm.value = true
}

function openEdit(cred: any) {
  editingCred.value = cred
  credForm.value = {
    name: cred.name || '',
    type: cred.type || 'password',
    username: cred.username || '',
    password: '',
    sshKeyId: cred.sshKeyId || null,
    domain: cred.domain || '',
  }
  credError.value = ''
  showForm.value = true
}

function closeForm() {
  showForm.value = false
  editingCred.value = null
}

async function handleCredSubmit() {
  if (!credForm.value.name.trim()) {
    credError.value = 'Name is required.'
    return
  }
  credSaving.value = true
  credError.value = ''
  try {
    const payload: any = {
      name: credForm.value.name.trim(),
      type: credForm.value.type,
      username: credForm.value.username.trim() || undefined,
      domain: credForm.value.domain.trim() || undefined,
    }
    if (credForm.value.type === 'password' && credForm.value.password) {
      payload.password = credForm.value.password
    }
    if (credForm.value.type === 'ssh_key' && credForm.value.sshKeyId) {
      payload.sshKeyId = credForm.value.sshKeyId
    }

    if (editingCred.value) {
      await vault.updateCredential(editingCred.value.id, payload)
    } else {
      await vault.createCredential(payload)
    }
    await load()
    closeForm()
  } catch (e: any) {
    credError.value = e?.data?.message || 'Save failed.'
  } finally {
    credSaving.value = false
  }
}

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>

    <!-- Inline Credential Form Modal -->
    <div v-if="showForm" class="fixed inset-0 flex items-center justify-center" style="z-index: 99999;">
      <div class="absolute inset-0 bg-black bg-opacity-70" @click="closeForm" />
      <div class="relative w-full max-w-lg mx-4 p-6 rounded-lg shadow-2xl" style="background: #1a1a2e; border: 2px solid #4a9eff;">
        <h3 class="text-lg font-semibold text-white mb-4">
          {{ editingCred ? 'Edit Credential' : 'New Credential' }}
        </h3>

        <div v-if="credError" class="mb-4 p-3 bg-red-900/50 border border-red-700 rounded text-red-300 text-sm">
          {{ credError }}
        </div>

        <div class="space-y-4">
          <div>
            <label class="block text-sm text-gray-400 mb-1">Name <span class="text-red-400">*</span></label>
            <input v-model="credForm.name" type="text" placeholder="e.g. prod-server-admin"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-blue-500 focus:outline-none text-sm" />
          </div>

          <div>
            <label class="block text-sm text-gray-400 mb-1">Type</label>
            <select v-model="credForm.type"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-blue-500 focus:outline-none text-sm">
              <option value="password">Password</option>
              <option value="ssh_key">SSH Key</option>
            </select>
          </div>

          <div>
            <label class="block text-sm text-gray-400 mb-1">Username</label>
            <input v-model="credForm.username" type="text" placeholder="e.g. admin"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-blue-500 focus:outline-none text-sm" />
          </div>

          <div v-if="credForm.type === 'password'">
            <label class="block text-sm text-gray-400 mb-1">
              Password <span v-if="editingCred" class="text-gray-600">(leave blank to keep current)</span>
            </label>
            <input v-model="credForm.password" type="password" placeholder="Enter password"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-blue-500 focus:outline-none text-sm" />
          </div>

          <div v-if="credForm.type === 'ssh_key'">
            <label class="block text-sm text-gray-400 mb-1">SSH Key</label>
            <select v-model="credForm.sshKeyId"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-blue-500 focus:outline-none text-sm">
              <option :value="null">— Select a key —</option>
              <option v-for="key in sshKeys" :key="key.id" :value="key.id">
                {{ key.name }} ({{ key.keyType || 'rsa' }})
              </option>
            </select>
            <p v-if="sshKeys.length === 0" class="text-xs text-gray-500 mt-1">
              No SSH keys in vault yet.
              <NuxtLink to="/vault/keys" class="text-blue-400 hover:underline">Import one first.</NuxtLink>
            </p>
          </div>

          <div>
            <label class="block text-sm text-gray-400 mb-1">Domain <span class="text-gray-600">(optional, for RDP)</span></label>
            <input v-model="credForm.domain" type="text" placeholder="e.g. CORP"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-blue-500 focus:outline-none text-sm" />
          </div>
        </div>

        <div class="flex justify-end gap-3 mt-6">
          <button @click="closeForm" class="px-4 py-2 text-sm text-gray-400 hover:text-white rounded border border-gray-600 hover:border-gray-400">
            Cancel
          </button>
          <button @click="handleCredSubmit" :disabled="credSaving"
            class="px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded disabled:opacity-50">
            {{ credSaving ? 'Saving...' : (editingCred ? 'Update' : 'Create') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
