<!-- Accordion item with schedule -->
<script setup lang="ts">
import { computed, inject, ref } from 'vue';
import { AppConfigType, ScheduleType } from '~src/admin/types';
import BaseSchedule from './BaseSchedule.vue';
import Button from '../base/Button.vue';
import IconArrowDown from '../icons/IconArrowDown.vue';
import IconTrash from '../icons/IconTrash.vue';
import Popup from '../layout/Popup.vue';
import IconWarning from '../icons/IconWarning.vue';
import Axios from '~src/shared/axios';
import { useNotificationStore } from '~src/admin/stores/useNotificationStore';
import { useGettext } from 'vue3-gettext';
import { useSchedulesStore } from '~src/admin/stores/useSchedulesStore';
import { useTokensStore } from '~src/admin/stores/useTokensStore';

// Translations
const { $gettext } = useGettext();

// Get plugin config
const config: AppConfigType = inject('pluginConfig');

// Show notification
const { addNotification } = useNotificationStore();

// Get schedule actions
const { editSchedule, removeSchedule } = useSchedulesStore();

// Get schedule actions
const { updateTokens } = useTokensStore();

// Props
const { schedule } = defineProps<{
    schedule: ScheduleType;
}>();

// Current schedule
const currentSchedule = ref<ScheduleType>(schedule);

// Get limit reached
const { isTokenLimitReached } = useTokensStore();

// Popup control
const deletePopup = ref<InstanceType<typeof Popup>>();

// Loading for delete end edit
const requestLoading = ref(false);

// Control accordion
const accordionActive = ref(false);

// Account type
const isAccountFree = inject<boolean>('isAccountFree');

// Account expired
const isAccountExpired = inject<boolean>('isAccountExpired');

// Remove schedule
const scheduleAction = async (action: 'EDIT' | 'DELETE') => {
    // Setup messages
    let successMsg = $gettext('Succesfully removed schedule');
    let errorMsg = $gettext('There was an error with deleting schedule!');

    if (action === 'EDIT') {
        successMsg = $gettext('Succesfully edited schedule');
        errorMsg = $gettext('There was an error while editing schedule!');
    }

    try {
        // Set loading
        requestLoading.value = true;

        // Get the schedule ID
        const scheduleID = schedule.id;

        // Set url and body
        let bodyBoostsite = {
            schedule_id: scheduleID,
            action: 'delete',
        };

        if (action === 'EDIT') {
            bodyBoostsite['schedule'] = currentSchedule.value;
            bodyBoostsite['action'] = 'edit';
        }

        // Change the schedule in Boostsite API
        const responseBoostsite = await Axios.post(`${config.rest.endpoints.boostsite}/schedules`, bodyBoostsite);

        // Check if the response is successful
        if (responseBoostsite.status !== 200 || !responseBoostsite.data.success) {
            throw new Error(`REST API error: ${responseBoostsite.status} - ${responseBoostsite.statusText}`);
        }

		// Update schedules in store
		if (action === 'DELETE') {
			// Remove schedule from store
			removeSchedule(scheduleID);
		} else if (action === 'EDIT') {
			// Update schedule in store
			editSchedule(currentSchedule.value);
		}

        // Show notificaiton
        addNotification({
            message: `${successMsg} ${currentSchedule.value.topic}!`,
            type: 'success',
        });

		// Refresh the tokens
		updateTokens();
    } catch (error) {
        console.error('Error during API call:', error);

        // Show error
        addNotification({
            message: errorMsg,
            type: 'danger',
        });
    } finally {
        // Set loading
        requestLoading.value = false;

        // Close popup
        deletePopup.value.closePopup();
    }
};

// Calculate article usage
const usedArticles = computed(() => {
    // Sum existing articles and the potential new ones
    let currentSum = 0;

    if (currentSchedule.value.advSchedule) {
        // Advanced schedule
        currentSum = Object.values(currentSchedule.value.advSchedule).reduce((sum, arr) => sum + arr.length, 0);
    } else if (!currentSchedule.value.advSchedule) {
        // Basic schedule
        currentSum = currentSchedule.value.days.length;
    }

    return currentSum;
});

// Store inital used articles
const initialUsedArticles = usedArticles.value;

// If the limit is reached can only save the articles that have less planned than previosly
const tokenLimitReached = computed(() => {
	if (isTokenLimitReached.value) {
		return usedArticles.value > initialUsedArticles;
	}
	return false;
});

// 'Article' correct form
const articleWord = computed(() => {
    return currentSchedule.value.days.length === 1 ? $gettext('article') : $gettext('articles');
});
</script>

<template>
    <div
        :class="[
            'border border-neutral-500 bg-white rounded-lg transition-colors',
            !accordionActive && 'hover:border-primary-500',
			requestLoading && 'pointer-events-none',
        ]"
    >
        <!-- Accordion trigger -->
        <div
            class="p-4 md:p-5 flex justify-between items-center gap-2.5 cursor-pointer"
            @click="accordionActive = !accordionActive"
        >
            <!-- Title -->
            <h2 class="text-[16px] lg:text-md leading-tight font-bold">{{ currentSchedule.topic }}</h2>

            <!-- Weekly articles -->
            <div class="flex items-center gap-3 lg:gap-5 text-base-200 text-xs lg:text-base">
                <span>{{ usedArticles }} {{ articleWord }} {{ $gettext('weekly') }}</span>
                <IconArrowDown :class="['text-base-500 transition-transform', accordionActive && 'rotate-180']" />
            </div>
        </div>
        <!-- Accordion trigger -->

        <!-- Accordion body -->
        <div :class="['grid grid-rows-[0fr] transition-all duration-500', accordionActive && 'grid-rows-[1fr]']">
            <div class="overflow-hidden">
                <div class="p-4 md:p-5">
                    <!-- Intro text -->
                    <div class="mb-5 text-center">
                        <h1 class="mb-1 text-md font-bold leading-tight">
                            {{ $gettext('When articles should be published?') }}
                        </h1>
                        <p class="text-base-200">
                            {{
                                $gettext(
                                    'We will generate and publish articles on your behalf on a given days and time.'
                                )
                            }}
                        </p>
                    </div>

                    <!-- Set schedule -->
                    <BaseSchedule
                        :schedule="currentSchedule"
                        :is-preview="true"
                        @update-schedule="(newSchedule : ScheduleType) => currentSchedule = newSchedule"
                    />

                    <!-- Schedule actions -->
                    <div class="max-w-[300px] mx-auto mt-5 text-center">
                        <Button
                            class="mb-4 w-full"
                            :text="$gettext('Save changes')"
                            size="large"
                            :disabled="isAccountFree || tokenLimitReached || isAccountExpired"
                            :loading="requestLoading"
                            @click.prevent="scheduleAction('EDIT')"
                        />

                        <Button
                            :text="$gettext('Delete schedule')"
                            type="danger"
                            :icon-position="'left'"
                            :has-background="false"
                            :disabled="isAccountFree || isAccountExpired"
                            @click.prevent="(isAccountFree || isAccountExpired) ? null : deletePopup.openPopup()"
                        >
                            <IconTrash />
                        </Button>
                    </div>
                </div>
            </div>
        </div>
        <!-- Accordion body -->

        <!-- Delete popup -->
        <Popup
            ref="deletePopup"
            :cancel-button-text="$gettext('Cancel')"
            :confirm-button-text="$gettext('Delete')"
            confirm-button-type="danger"
            size="small"
            @popup-confirm="scheduleAction('DELETE')"
            :loading="requestLoading"
        >
            <div class="text-center">
                <IconWarning class="mb-4 mx-auto" />
                <h2 class="text-lg leading-lg font-bold">{{ $gettext('Are you sure?') }}</h2>
                <p>{{ $gettext("Deleted schedule can't be restored.") }}</p>
            </div>
        </Popup>
    </div>
</template>

<style scoped></style>
