<template>
  <BaseModal
    :show="show"
    aria-labelledby="add-user-title"
    @close="$emit('close')"
  >
    <div class="kestrel-card-modal w-full max-w-sm p-4">
      <h3
        id="add-user-title"
        class="mb-3 text-sm font-medium text-kestrel-text"
      >
        Add user
      </h3>
      <form @submit.prevent="onSubmit">
        <div class="mb-3 flex flex-col gap-1">
          <label
            for="add-identifier"
            class="text-xs text-kestrel-muted"
          >Username</label>
          <input
            id="add-identifier"
            v-model="form.identifier"
            type="text"
            required
            autocomplete="username"
            class="kestrel-input"
            placeholder="username"
          >
        </div>
        <div class="mb-3 flex flex-col gap-1">
          <label
            for="add-password"
            class="text-xs text-kestrel-muted"
          >Password</label>
          <input
            id="add-password"
            v-model="form.password"
            type="password"
            required
            autocomplete="new-password"
            class="kestrel-input"
            placeholder="••••••••"
          >
        </div>
        <div class="mb-4 flex flex-col gap-1">
          <label
            for="add-role"
            class="text-xs text-kestrel-muted"
          >Role</label>
          <select
            id="add-role"
            v-model="form.role"
            class="kestrel-input"
          >
            <option value="member">
              member
            </option>
            <option value="leader">
              leader
            </option>
            <option value="admin">
              admin
            </option>
          </select>
        </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"
          >
            Add user
          </button>
        </div>
      </form>
    </div>
  </BaseModal>
</template>

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

const props = defineProps({
  show: Boolean,
  submitError: { type: String, default: '' },
})

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

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

watch(() => props.show, (show) => {
  if (show) form.value = { identifier: '', password: '', role: 'member' }
})

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