<template>
  <BaseModal
    :show="!!user"
    aria-labelledby="edit-user-title"
    @close="$emit('close')"
  >
    <div
      v-if="user"
      class="kestrel-card-modal w-full max-w-sm p-4"
    >
      <h3
        id="edit-user-title"
        class="mb-3 text-sm font-medium text-kestrel-text"
      >
        Edit local user
      </h3>
      <form @submit.prevent="onSubmit">
        <div class="mb-3 flex flex-col gap-1">
          <label
            for="edit-identifier"
            class="text-xs text-kestrel-muted"
          >Identifier</label>
          <input
            id="edit-identifier"
            v-model="form.identifier"
            type="text"
            required
            class="kestrel-input"
          >
        </div>
        <div class="mb-4 flex flex-col gap-1">
          <label
            for="edit-password"
            class="text-xs text-kestrel-muted"
          >New password (leave blank to keep)</label>
          <input
            id="edit-password"
            v-model="form.password"
            type="password"
            autocomplete="new-password"
            class="kestrel-input"
            placeholder="••••••••"
          >
          <p class="mt-0.5 text-xs text-kestrel-muted">
            If you change your password, use the new one next time you sign in.
          </p>
        </div>
        <p
          v-if="submitError"
          class="mb-2 text-xs text-red-400"
        >
          {{ submitError }}
        </p>
        <div class="flex justify-end gap-2">
          <button
            type="button"
            class="kestrel-btn-secondary"
            @click="$emit('close')"
          >
            Cancel
          </button>
          <button
            type="submit"
            class="rounded border border-kestrel-accent px-3 py-1.5 text-sm text-kestrel-accent hover:bg-kestrel-accent-dim"
          >
            Save
          </button>
        </div>
      </form>
    </div>
  </BaseModal>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  user: { type: Object, default: null },
  submitError: { type: String, default: '' },
})

const emit = defineEmits(['close', 'submit'])

const form = ref({ identifier: '', password: '' })

watch(() => props.user, (u) => {
  if (u) form.value = { identifier: u.identifier, password: '' }
}, { immediate: true })

function onSubmit() {
  const payload = { identifier: form.value.identifier.trim() }
  if (form.value.password) payload.password = form.value.password
  emit('submit', payload)
}
</script>
