<template>
  <q-card
    bordered
    style="position: relative; min-height: 3em"
    :class="{ 'cursor-pointer': modelValue.link }"
    @click="click"
  >
    <q-btn
      v-if="modelValue.accept !== undefined"
      round
      dense
      icon="mdi-trash-can"
      size="sm"
      color="negative"
      class="q-ma-xs"
      title="Löschen"
      style="position: absolute; top: 0; right: 0"
      @click="dismiss"
    />
    <q-card-section class="q-pa-xs">
      <div class="text-overline">{{ dateString }}</div>
      <q-item style="padding: 1px">
        <q-item-section v-if="modelValue.icon" side
          ><q-icon color="primary" :name="modelValue.icon"
        /></q-item-section>
        <q-item-section>{{ modelValue.text }}</q-item-section>
      </q-item>
    </q-card-section>
    <q-card-actions v-if="modelValue.reject || modelValue.accept">
      <q-btn
        v-if="modelValue.accept"
        icon="mdi-check"
        color="positive"
        label="Annehmen"
        flat
        dense
        size="sm"
        @click="accept"
      />
      <q-btn
        v-if="modelValue.reject"
        icon="mdi-close"
        color="negative"
        label="Ablehnen"
        flat
        dense
        size="sm"
        @click="reject"
      />
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import { defineComponent, PropType, computed } from 'vue';
import { formatDateTime } from '@flaschengeist/api';
import { FG_Plugin } from '@flaschengeist/types';
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'Notification',
  props: {
    modelValue: {
      required: true,
      type: Object as PropType<FG_Plugin.Notification>,
    },
  },
  emits: {
    remove: (id: number) => !!id,
  },
  setup(props, { emit }) {
    const router = useRouter();
    const dateString = computed(() => formatDateTime(props.modelValue.time, true, true));

    async function click() {
      if (props.modelValue.link) await router.push(props.modelValue.link);
    }

    function accept() {
      if (typeof props.modelValue.accept === 'function')
        void props.modelValue.accept().finally(() => emit('remove', props.modelValue.id));
      else emit('remove', props.modelValue.id);
    }

    function reject() {
      if (typeof props.modelValue.reject === 'function')
        void props.modelValue.reject().finally(() => emit('remove', props.modelValue.id));
      else emit('remove', props.modelValue.id);
    }

    function dismiss() {
      if (typeof props.modelValue.dismiss === 'function')
        void props.modelValue.dismiss().finally(() => emit('remove', props.modelValue.id));
      else emit('remove', props.modelValue.id);
    }

    return { accept, click, dateString, dismiss, reject };
  },
});
</script>

<style scoped></style>
