<template>
  <v-menu>
    <template #activator="{ props: menuProps }">
      <v-btn
        icon
        variant="text"
        density="comfortable"
        size="default"
        v-bind="menuProps"
      >
        <v-icon icon="mdi-dots-vertical" />
      </v-btn>
    </template>
    <v-list density="compact">
      <v-list-item
        prepend-icon="mdi-folder-plus-outline"
        title="Add subdeck"
        @click="openAddSubdeck"
      />
      <v-list-item
        prepend-icon="mdi-pencil-outline"
        title="Edit deck"
        @click="openEdit"
      />
      <v-list-item
        prepend-icon="mdi-delete-outline"
        title="Delete this deck"
        class="text-error"
        @click="openDelete"
      />
    </v-list>
  </v-menu>

  <v-dialog
    v-model="showAddSubdeck"
    width="400"
  >
    <v-form
      ref="addFormRef"
      @submit.prevent="createSubdeck"
    >
      <v-card>
        <v-card-title>Add Sub-Deck</v-card-title>
        <v-card-text>
          <v-text-field
            v-model="newDeckName"
            label="Name"
            autofocus
            :rules="[required]"
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            variant="text"
            text="Cancel"
            @click="showAddSubdeck = false"
          />
          <v-btn
            type="submit"
            color="primary"
            variant="flat"
            :loading="isSubmitting"
            text="Create"
          />
        </v-card-actions>
      </v-card>
    </v-form>
  </v-dialog>

  <v-dialog
    v-model="showEdit"
    width="400"
  >
    <v-form
      ref="editFormRef"
      @submit.prevent="updateDeck"
    >
      <v-card>
        <v-card-title>Edit Deck</v-card-title>
        <v-card-text>
          <v-text-field
            v-model="editName"
            label="Name"
            autofocus
            :rules="[required]"
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn
            variant="text"
            text="Cancel"
            @click="showEdit = false"
          />
          <v-btn
            type="submit"
            color="primary"
            variant="flat"
            :loading="isSubmitting"
            text="Save"
          />
        </v-card-actions>
      </v-card>
    </v-form>
  </v-dialog>

  <v-dialog
    v-model="showDelete"
    width="400"
  >
    <v-card>
      <v-card-title>Delete Deck</v-card-title>
      <v-card-text>Are you sure you want to delete this deck?</v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn
          variant="text"
          text="Cancel"
          @click="showDelete = false"
        />
        <v-btn
          color="error"
          variant="flat"
          :loading="isSubmitting"
          text="Delete"
          @click="deleteDeck"
        />
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue"
import { VForm } from "vuetify/components"

import { required } from "@/utils/validators"
import flashcardDecksApi from "@/api/flashcard-decks-api"
import useSnack from "@/use/use-snack"

const props = defineProps<{
  flashcardDeckId: number
}>()

const emit = defineEmits<{
  created: [flashcardDeckId: number]
  updated: [flashcardDeckId: number]
  deleted: [flashcardDeckId: number]
}>()

const snack = useSnack()
const isSubmitting = ref(false)

// Add subdeck
const showAddSubdeck = ref(false)
const newDeckName = ref("")
const addFormRef = ref<InstanceType<typeof VForm> | null>(null)

function openAddSubdeck() {
  newDeckName.value = ""
  showAddSubdeck.value = true
}

async function createSubdeck() {
  if (!addFormRef.value) return
  const { valid } = await addFormRef.value.validate()
  if (!valid) return

  try {
    isSubmitting.value = true
    const { flashcardDeck } = await flashcardDecksApi.create({
      name: newDeckName.value,
      parentDeckId: props.flashcardDeckId,
    })
    emit("created", flashcardDeck.id)
    showAddSubdeck.value = false
    snack.success("Sub-deck created")
  } catch {
    snack.error("Failed to create sub-deck")
  } finally {
    isSubmitting.value = false
  }
}

// Edit deck
const showEdit = ref(false)
const editName = ref("")
const editFormRef = ref<InstanceType<typeof VForm> | null>(null)

async function openEdit() {
  try {
    const { flashcardDeck } = await flashcardDecksApi.get(props.flashcardDeckId)
    editName.value = flashcardDeck.name
    showEdit.value = true
  } catch {
    snack.error("Failed to load deck")
  }
}

async function updateDeck() {
  if (!editFormRef.value) return
  const { valid } = await editFormRef.value.validate()
  if (!valid) return

  try {
    isSubmitting.value = true
    await flashcardDecksApi.update(props.flashcardDeckId, { name: editName.value })
    emit("updated", props.flashcardDeckId)
    showEdit.value = false
    snack.success("Deck updated")
  } catch {
    snack.error("Failed to update deck")
  } finally {
    isSubmitting.value = false
  }
}

// Delete deck
const showDelete = ref(false)

function openDelete() {
  showDelete.value = true
}

async function deleteDeck() {
  try {
    isSubmitting.value = true
    await flashcardDecksApi.delete(props.flashcardDeckId)
    emit("deleted", props.flashcardDeckId)
    showDelete.value = false
    snack.success("Deck deleted")
  } catch {
    snack.error("Failed to delete deck")
  } finally {
    isSubmitting.value = false
  }
}
</script>
