<template>
  <div class="container mx-auto p-4 max-w-lg">
    <h1 class="text-2xl font-bold mb-6">{{ isNew ? 'New user' : `Edit ${username}` }}</h1>

    <form @submit.prevent="submit" class="flex flex-col gap-4">
      <fieldset class="fieldset">
        <label class="label" for="user">Username</label>
        <input
          id="user"
          v-model="form.user"
          type="text"
          class="input"
          required
          :readonly="!isNew"
        />
      </fieldset>
      <PasswordInput
        v-model="form.pass"
        label="Password (leave blank to keep)"
        autocomplete="new-password"
      />
      <fieldset class="fieldset">
        <label class="label">Auths</label>
        <div class="flex flex-wrap gap-2">
          <label v-for="a of authOptions" :key="a" class="label cursor-pointer gap-2" :for="`auth-${a}`">
            <input :id="`auth-${a}`" v-model="form.auths" type="checkbox" :value="a" class="checkbox checkbox-sm" />
            <span>{{ a }}</span>
          </label>
        </div>
      </fieldset>
      <p v-if="error" class="text-error text-sm">{{ error }}</p>
      <div class="flex gap-2">
        <button type="submit" class="btn btn-primary" :disabled="loading">
          <span v-if="loading" class="loading loading-spinner loading-sm" />
          <span v-else>Save</span>
        </button>
        <NuxtLink to="/admin" class="btn btn-ghost">Back</NuxtLink>
        <button
          v-if="!isNew"
          type="button"
          class="btn btn-error btn-outline ml-auto"
          :disabled="loading"
          @click="confirmDelete"
        >
          Delete
        </button>
      </div>
    </form>

    <dialog ref="deleteModalRef" class="modal">
      <div class="modal-box">
        <p>Delete user {{ form.user }}?</p>
        <div class="modal-action">
          <form method="dialog">
            <button class="btn">Cancel</button>
          </form>
          <button class="btn btn-error" :disabled="deleting" @click="doDelete">Delete</button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop"><button aria-label="Close">Close</button></form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
definePageMeta({ middleware: 'admin' })

const route = useRoute()
const router = useRouter()
const api = useMapApi()
const username = computed(() => (route.params.username as string) ?? '')
const isNew = computed(() => username.value === 'new')

const form = ref({ user: '', pass: '', auths: [] as string[] })
const authOptions = ['admin', 'map', 'markers', 'upload']
const loading = ref(false)
const deleting = ref(false)
const error = ref('')
const deleteModalRef = ref<HTMLDialogElement | null>(null)

onMounted(async () => {
  if (!isNew.value) {
    form.value.user = username.value
    try {
      const u = await api.adminUserByName(username.value)
      form.value.auths = u.auths ?? []
    } catch {
      error.value = 'Failed to load user'
    }
  }
})

async function submit() {
  error.value = ''
  loading.value = true
  try {
    await api.adminUserPost({
      user: form.value.user,
      pass: form.value.pass || undefined,
      auths: form.value.auths,
    })
    await router.push('/admin')
  } catch (e: unknown) {
    error.value = e instanceof Error ? e.message : 'Failed'
  } finally {
    loading.value = false
  }
}

function confirmDelete() {
  deleteModalRef.value?.showModal()
}

async function doDelete() {
  deleting.value = true
  try {
    await api.adminUserDelete(form.value.user)
    deleteModalRef.value?.close()
    await router.push('/admin')
  } catch (e: unknown) {
    error.value = e instanceof Error ? e.message : 'Delete failed'
  } finally {
    deleting.value = false
  }
}
</script>
