<script setup lang="ts">
import { Capacitor } from '@capacitor/core'
import { Dialog } from '@capacitor/dialog'
import type { ConfirmOptions } from '@capacitor/dialog'
import { vibrate } from '@/composables/useHaptics'

const props = defineProps<{
    note: Note
}>()

type ActionKey = 'delete' | 'setRoot'

interface ModalOptions {
    key: ActionKey
    icon: string
    confirmOptions: ConfirmOptions
}

const confirmModals: ModalOptions[] = [
    {
        key: 'delete',
        icon: 'fas fa-fw fa-trash',
        confirmOptions: {
            title: 'Delete note',
            message: 'Are you sure you want to delete this note?',
            okButtonTitle: 'Delete note'
        }
    },
    {
        key: 'setRoot',
        icon: 'fas fa-fw fa-sitemap',
        confirmOptions: {
            title: 'Set root note',
            message: 'Are you sure you want to set this note as root note?',
            okButtonTitle: 'Set note as root note'
        }
    }
]

const emit = defineEmits<{
    execute: [actionType: ActionKey, close?: () => Promise<void>]
}>()

const openModal = async (open: () => void, modal: ModalOptions) => {
    if (['android', 'ios'].includes(Capacitor.getPlatform())) {
        const { value: confirmed } = await Dialog.confirm(modal.confirmOptions)
        if (confirmed) emit('execute', modal.key)
    } else {
        open()
    }
}
</script>
<template>
    <div class="mb-2 flex items-center space-x-2">
        <h1 class="flex flex-grow items-center rounded-md text-3xl font-semibold hover:bg-gray-200">
            <slot name="title"></slot>
        </h1>
        <UIButtonGroup class="flex items-center" v-if="!props.note.isRoot">
            <UIModal v-for="confirmModal in confirmModals" :key="confirmModal.key">
                <template #activator="{ open }">
                    <UIButton
                        size="sm"
                        @click="openModal(open, confirmModal)"
                        @mousedown="vibrate"
                        join
                    >
                        <i :class="confirmModal.icon" />
                    </UIButton>
                </template>
                <template #title>
                    <i class="mr-2" :class="confirmModal.icon" />
                    {{ confirmModal.confirmOptions.title }}
                </template>
                <template #default>{{ confirmModal.confirmOptions.message }}</template>
                <template #actions="{ close }">
                    <UIButton size="sm" @click="close">Cancel</UIButton>
                    <UIButton
                        size="sm"
                        color="primary"
                        @click="emit('execute', confirmModal.key, close)"
                    >
                        {{ confirmModal.confirmOptions.okButtonTitle }}
                    </UIButton>
                </template>
            </UIModal>
        </UIButtonGroup>
    </div>
</template>
