<script setup>
import { onMounted, ref, inject, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';

import VnImg from 'src/components/ui/VnImg.vue';
import VnForm from 'src/components/common/VnForm.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';

import { useAppStore } from 'stores/app';
import { storeToRefs } from 'pinia';

const jApi = inject('jApi');
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const appStore = useAppStore();
const { isHeaderMounted } = storeToRefs(appStore);

const newsTags = ref([]);
const pks = computed(() => ({ id: route.params.id }));
const isEditMode = !!route.params.id;
const formData = ref(
    !route.params.id
        ? {
              title: '',
              tag: '',
              priority: '',
              text: ''
          }
        : undefined
);

const fetchNewDataSql = computed(() => {
    if (!route.params.id) return undefined;
    return {
        query: `
        SELECT id, title, text, tag, priority, image
        FROM news WHERE id = #id`,
        params: { id: route.params.id }
    };
});

const getNewsTag = async () => {
    try {
        newsTags.value = await jApi.query(
            `SELECT name, description FROM newsTag
            ORDER BY description`
        );
    } catch (error) {
        console.error('Error getting newsTag:', error);
    }
};

const goBack = () => router.push({ name: 'adminNews' });

onMounted(async () => {
    getNewsTag();
});
</script>

<template>
    <QPage class="vn-w-sm">
        <Teleport v-if="isHeaderMounted" to="#actions">
            <QBtn
                :label="t('back')"
                icon="close"
                rounded
                no-caps
                @click="goBack()"
            >
                <QTooltip>{{ t('back') }}</QTooltip>
            </QBtn>
        </Teleport>
        <VnForm
            ref="vnFormRef"
            :fetch-form-data-sql="fetchNewDataSql"
            :form-initial-data="formData"
            :create-model-default="{
                field: 'userFk',
                value: 'account.myUser_getId()'
            }"
            :pks="pks"
            :is-edit-mode="isEditMode"
            table="news"
            schema="hedera"
            separation-between-inputs="lg"
            @on-data-saved="goBack()"
        >
            <template #form="{ data }">
                <VnImg
                    :id="data.image"
                    :edit-image-name="data.image"
                    storage="news"
                    edit-schema="news"
                    size="200x200"
                    width="80px"
                    height="80px"
                    class="full-width"
                    rounded
                    editable
                    always-show-edit-button
                />
                <VnInput
                    v-model="data.title"
                    :label="t('title')"
                    :clearable="false"
                    data-testid="newsTitleInput"
                />
                <div class="row justify-between q-gutter-x-md">
                    <VnSelect
                        v-model="data.tag"
                        :label="t('tag')"
                        option-label="description"
                        option-value="name"
                        :options="newsTags"
                        class="col"
                        data-testid="newsTagSelect"
                    />
                    <VnInput
                        v-model="data.priority"
                        :label="t('priority')"
                        :clearable="false"
                        class="col"
                        data-testid="newsPriorityInput"
                    />
                </div>
                <QEditor
                    v-model="data.text"
                    :toolbar="[
                        [
                            {
                                label: $q.lang.editor.align,
                                icon: $q.iconSet.editor.align,
                                fixedLabel: true,
                                options: ['left', 'center', 'right', 'justify']
                            }
                        ],
                        [
                            'bold',
                            'italic',
                            'strike',
                            'underline',
                            'subscript',
                            'superscript'
                        ],
                        ['token', 'hr', 'link', 'custom_btn'],
                        ['print', 'fullscreen'],
                        [
                            {
                                label: $q.lang.editor.formatting,
                                icon: $q.iconSet.editor.formatting,
                                list: 'no-icons',
                                options: [
                                    'p',
                                    'h1',
                                    'h2',
                                    'h3',
                                    'h4',
                                    'h5',
                                    'h6',
                                    'code'
                                ]
                            },
                            {
                                label: $q.lang.editor.fontSize,
                                icon: $q.iconSet.editor.fontSize,
                                fixedLabel: true,
                                fixedIcon: true,
                                list: 'no-icons',
                                options: [
                                    'size-1',
                                    'size-2',
                                    'size-3',
                                    'size-4',
                                    'size-5',
                                    'size-6',
                                    'size-7'
                                ]
                            },
                            {
                                label: $q.lang.editor.defaultFont,
                                icon: $q.iconSet.editor.font,
                                fixedIcon: true,
                                list: 'no-icons',
                                options: [
                                    'default_font',
                                    'arial',
                                    'arial_black',
                                    'comic_sans',
                                    'courier_new',
                                    'impact',
                                    'lucida_grande',
                                    'times_new_roman',
                                    'verdana'
                                ]
                            },
                            'removeFormat'
                        ],
                        ['quote', 'unordered', 'ordered', 'outdent', 'indent'],

                        ['undo', 'redo'],
                        ['viewsource']
                    ]"
                    :fonts="{
                        arial: 'Arial',
                        arial_black: 'Arial Black',
                        comic_sans: 'Comic Sans MS',
                        courier_new: 'Courier New',
                        impact: 'Impact',
                        lucida_grande: 'Lucida Grande',
                        times_new_roman: 'Times New Roman',
                        verdana: 'Verdana'
                    }"
                />
            </template>
        </VnForm>
    </QPage>
</template>

<i18n lang="yaml">
en-US:
    addNew: Add new
    confirmDeleteAddress: Are you sure you want to delete this new?
    title: Title
    tag: Tag
    priority: Priority
es-ES:
    addNew: Añadir noticia
    confirmDeleteAddress: ¿Estás seguro de que quieres eliminar esta noticia?
    title: Título
    tag: Etiqueta
    priority: Prioridad
ca-ES:
    addNew: Afegir noticia
    confirmDeleteAddress: Estàs segur que vols eliminar aquesta notícia?
    title: Títol
    tag: Etiqueta
    priority: Prioritat
fr-FR:
    addNew: Ajouter nouvelles
    confirmDeleteAddress: Êtes-vous sûr de vouloir supprimer cette nouvelle?
    title: Titre
    tag: Tag
    priority: Priorité
pt-PT:
    addNew: Adicionar noticia
    confirmDeleteAddress: Tem a certeza que deseja eliminar esta notícia?
    title: Título
    tag: Etiqueta
    priority: Prioridade
</i18n>
