<template>
  <UModal v-model:open="open" :title="`Suggest a ${pool} tag`" :dismissible="true">
    <template #body>
      <div class="suggest-modal-body">
        <div v-if="success" class="success-msg">
          Thanks! We'll review your suggestion.
        </div>
        <form v-else @submit.prevent="submit" class="suggest-form">
          <div class="field">
            <label>Tag name</label>
            <input
              v-model="tagName"
              type="text"
              placeholder="e.g., Game Narrative Design"
              required
              :disabled="submitting"
            />
          </div>
          <div class="form-actions">
            <button type="submit" class="btn btn-primary" :disabled="submitting || !tagName.trim()">
              {{ submitting ? "Sending..." : "Submit suggestion" }}
            </button>
            <button type="button" class="btn" @click="open = false">Cancel</button>
          </div>
          <p v-if="error" class="error-msg">{{ error }}</p>
        </form>
      </div>
    </template>
  </UModal>
</template>

<script setup>
const props = defineProps({
  pool: { type: String, default: "" },
});

const emit = defineEmits(["close"]);

const open = defineModel("open", { default: false });

const tagName = ref("");
const submitting = ref(false);
const success = ref(false);
const error = ref(null);

watch(open, (val) => {
  if (!val) {
    // reset state when closed
    tagName.value = "";
    submitting.value = false;
    success.value = false;
    error.value = null;
  }
});

async function submit() {
  if (!tagName.value.trim()) return;
  submitting.value = true;
  error.value = null;
  try {
    await $fetch("/api/tags/suggest", {
      method: "POST",
      body: { label: tagName.value.trim(), pool: props.pool },
    });
    success.value = true;
  } catch (e) {
    error.value = e?.data?.message || "Something went wrong. Please try again.";
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped>
.suggest-modal-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggest-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.success-msg {
  font-size: 12px;
  font-family: "Commit Mono", monospace;
  color: var(--green);
  padding: 8px 0;
}

.error-msg {
  font-size: 11px;
  font-family: "Commit Mono", monospace;
  color: var(--ember);
  margin: 0;
}
</style>
