<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 VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
import FormModel from 'src/components/common/FormModel.vue';

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

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

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

const initialFetchUrl = computed(() => {
    if (!route.params.id) return undefined;
    return `news/${route.params.id}`;
});

const urlUpdate = computed(() => {
    if (!route.params.id) return undefined;
    return `news/${route.params.id}`;
});

const urlCreate = computed(() => {
    if (route.params.id) return undefined;
    return 'news';
});

const getNewsTag = async () => {
    try {
        const { data } = await api.get('newsTags');
        newsTags.value = data;
    } 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>
        <FormModel
            :form-initial-data="formData"
            :url="initialFetchUrl"
            :auto-load="isEditMode"
            :url-create="urlCreate"
            :url-update="urlUpdate"
            :data-required="{ userFk: userStore.userId }"
            :show-bottom-actions="false"
            @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-cy="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-cy="newsTagSelect"
                    />
                    <VnInput
                        v-model="data.priority"
                        :label="t('priority')"
                        :clearable="false"
                        class="col"
                        data-cy="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>
        </FormModel>
    </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>
