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

const keys = ref<any[]>([])
const loading = ref(true)
const showImport = ref(false)
const deletingId = ref<number | null>(null)

// Inline import form state
const importForm = ref({
  name: '',
  privateKey: '',
  publicKey: '',
  passphrase: '',
})
const importSaving = ref(false)
const importError = ref('')

async function load() {
  loading.value = true
  try {
    keys.value = (await vault.listKeys()) as any[]
  } finally {
    loading.value = false
  }
}

function openImport() {
  importForm.value = { name: '', privateKey: '', publicKey: '', passphrase: '' }
  importError.value = ''
  showImport.value = true
}

function closeImport() {
  showImport.value = false
}

async function handleImportSubmit() {
  if (!importForm.value.name.trim() || !importForm.value.privateKey.trim()) {
    importError.value = 'Name and private key are required.'
    return
  }
  importSaving.value = true
  importError.value = ''
  try {
    await vault.importKey({
      name: importForm.value.name.trim(),
      privateKey: importForm.value.privateKey.trim(),
      publicKey: importForm.value.publicKey.trim() || undefined,
      passphrase: importForm.value.passphrase || undefined,
    })
    await load()
    closeImport()
  } catch (e: any) {
    importError.value = e?.data?.message || 'Import failed.'
  } finally {
    importSaving.value = false
  }
}

function handleFileUpload(field: 'privateKey' | 'publicKey', event: Event) {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return
  const reader = new FileReader()
  reader.onload = (e) => {
    importForm.value[field] = e.target?.result as string
  }
  reader.readAsText(file)
}

async function confirmDelete(key: any) {
  if (!confirm(`Delete SSH key "${key.name}"? This cannot be undone.`)) return
  deletingId.value = key.id
  try {
    await vault.deleteKey(key.id)
    await load()
  } finally {
    deletingId.value = null
  }
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
}

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">SSH Keys</h2>
      </div>
      <button @click="openImport"
        class="px-3 py-1.5 bg-wraith-600 hover:bg-wraith-700 text-white text-sm rounded">
        Import Key
      </button>
    </div>

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

    <div v-else-if="keys.length === 0" class="text-center py-12 text-gray-600">
      <p>No SSH keys yet.</p>
      <button @click="openImport" class="mt-3 text-wraith-400 hover:text-wraith-300 text-sm">
        Import your first key
      </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">Type</th>
            <th class="text-left px-4 py-3 font-medium">Fingerprint</th>
            <th class="text-left px-4 py-3 font-medium">Created</th>
            <th class="px-4 py-3"></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="key in keys" :key="key.id"
            class="border-b border-gray-700/50 hover:bg-gray-700/30">
            <td class="px-4 py-3 text-white font-medium">{{ key.name }}</td>
            <td class="px-4 py-3">
              <span class="px-2 py-0.5 bg-gray-700 text-gray-300 rounded text-xs font-mono">
                {{ key.keyType || 'rsa' }}
              </span>
            </td>
            <td class="px-4 py-3 text-gray-400 font-mono text-xs">
              {{ key.fingerprint || '—' }}
            </td>
            <td class="px-4 py-3 text-gray-400">{{ formatDate(key.createdAt) }}</td>
            <td class="px-4 py-3 text-right">
              <button @click="confirmDelete(key)"
                :disabled="deletingId === key.id"
                class="text-xs text-red-400 hover:text-red-300 disabled:opacity-50">
                {{ deletingId === key.id ? 'Deleting...' : 'Delete' }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Inline Import Key Modal -->
    <div v-if="showImport" class="fixed inset-0 flex items-center justify-center" style="z-index: 99999;">
      <div class="absolute inset-0 bg-black bg-opacity-70" @click="closeImport" />
      <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">Import SSH Key</h3>

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

        <div class="space-y-4">
          <div>
            <label class="block text-sm text-gray-400 mb-1">Key Name <span class="text-red-400">*</span></label>
            <input v-model="importForm.name" type="text" placeholder="e.g. my-server-key"
              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">Private Key <span class="text-red-400">*</span></label>
            <textarea v-model="importForm.privateKey" rows="6" placeholder="-----BEGIN RSA PRIVATE KEY-----..."
              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 font-mono resize-none" />
            <div class="mt-1 flex items-center gap-2">
              <label class="text-xs text-gray-500 cursor-pointer hover:text-gray-300">
                <input type="file" class="hidden" accept=".pem,.key,id_rsa,id_ed25519,id_ecdsa"
                  @change="handleFileUpload('privateKey', $event)" />
                Upload from file
              </label>
            </div>
          </div>

          <div>
            <label class="block text-sm text-gray-400 mb-1">Public Key <span class="text-gray-600">(optional)</span></label>
            <textarea v-model="importForm.publicKey" rows="2" placeholder="ssh-rsa AAAA..."
              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 font-mono resize-none" />
            <div class="mt-1">
              <label class="text-xs text-gray-500 cursor-pointer hover:text-gray-300">
                <input type="file" class="hidden" accept=".pub"
                  @change="handleFileUpload('publicKey', $event)" />
                Upload from file
              </label>
            </div>
          </div>

          <div>
            <label class="block text-sm text-gray-400 mb-1">Passphrase <span class="text-gray-600">(optional)</span></label>
            <input v-model="importForm.passphrase" type="password" placeholder="Leave blank if unencrypted"
              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="closeImport" 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="handleImportSubmit" :disabled="importSaving"
            class="px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded disabled:opacity-50">
            {{ importSaving ? 'Importing...' : 'Import Key' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
