<script setup lang="ts">
const props = defineProps<{
  visible: boolean
  credential: any | null
  sshKeys: any[]
}>()

const emit = defineEmits<{
  'update:visible': [boolean]
  saved: []
}>()

const vault = useVault()

const form = ref({
  name: '',
  type: 'password' as 'password' | 'ssh_key',
  username: '',
  password: '',
  sshKeyId: null as number | null,
  domain: '',
})
const saving = ref(false)
const error = ref('')

const isEdit = computed(() => !!props.credential)

watch(() => props.visible, (val) => {
  if (val) {
    if (props.credential) {
      form.value = {
        name: props.credential.name || '',
        type: props.credential.type || 'password',
        username: props.credential.username || '',
        password: '',
        sshKeyId: props.credential.sshKeyId || null,
        domain: props.credential.domain || '',
      }
    } else {
      form.value = { name: '', type: 'password', username: '', password: '', sshKeyId: null, domain: '' }
    }
    error.value = ''
  }
})

function close() {
  emit('update:visible', false)
}

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

    if (isEdit.value) {
      await vault.updateCredential(props.credential.id, payload)
    } else {
      await vault.createCredential(payload)
    }
    emit('saved')
    close()
  } catch (e: any) {
    error.value = e?.data?.message || 'Save failed.'
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <Teleport to="body">
    <div v-if="visible" class="fixed inset-0 z-50 flex items-center justify-center">
      <div class="absolute inset-0 bg-black/60" @click="close" />
      <div class="relative bg-gray-800 rounded-lg border border-gray-700 w-full max-w-lg mx-4 p-6 shadow-xl">
        <h3 class="text-lg font-semibold text-white mb-4">
          {{ isEdit ? 'Edit Credential' : 'New Credential' }}
        </h3>

        <div v-if="error" class="mb-4 p-3 bg-red-900/50 border border-red-700 rounded text-red-300 text-sm">
          {{ error }}
        </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="form.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-wraith-500 focus:outline-none text-sm" />
          </div>

          <div>
            <label class="block text-sm text-gray-400 mb-1">Type</label>
            <select v-model="form.type"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-wraith-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="form.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-wraith-500 focus:outline-none text-sm" />
          </div>

          <div v-if="form.type === 'password'">
            <label class="block text-sm text-gray-400 mb-1">
              Password <span v-if="isEdit" class="text-gray-600">(leave blank to keep current)</span>
            </label>
            <input v-model="form.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-wraith-500 focus:outline-none text-sm" />
          </div>

          <div v-if="form.type === 'ssh_key'">
            <label class="block text-sm text-gray-400 mb-1">SSH Key</label>
            <select v-model="form.sshKeyId"
              class="w-full bg-gray-900 text-white px-3 py-2 rounded border border-gray-600 focus:border-wraith-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-wraith-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="form.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-wraith-500 focus:outline-none text-sm" />
          </div>
        </div>

        <div class="flex justify-end gap-3 mt-6">
          <button @click="close" 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="handleSubmit" :disabled="saving"
            class="px-4 py-2 text-sm bg-wraith-600 hover:bg-wraith-700 text-white rounded disabled:opacity-50">
            {{ saving ? 'Saving...' : (isEdit ? 'Update' : 'Create') }}
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>
