<!-- Summary view -->
<script setup lang="ts">
import { AppConfigType, PostType, ScheduleType } from '~src/admin/types';
import { inject, ref } from 'vue';
import Button from '../base/Button.vue';
import IconArrowLeft from '../icons/IconArrowLeft.vue';
import Card from '../layout/Card.vue';
import PostsTable from '../posts/PostsTable.vue';
import Axios from '~src/shared/axios';
import { useRouter } from 'vue-router';
import { useNotificationStore } from '~src/admin/stores/useNotificationStore';
import Message from '../base/Message.vue';
import { useGettext } from 'vue3-gettext';
import { useSchedulesStore } from '~src/admin/stores/useSchedulesStore';

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

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

// Get schedule actions
const { addSchedule } = useSchedulesStore();

// Router
const router = useRouter();

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

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

// Emits
const emit = defineEmits<{
    previousStep: [];
    updateSchedule: [schedule: ScheduleType];
}>();

// Loading
const loading = ref(false);

// Get the date of the given weekday
const getDateOfPublication = (weekday: string, time: string) => {
    const today = new Date();

    // Get the next instance of the weekday
    const currentDay = today.getDay();
    let daysUntilNext = (Number(weekday) + 7 - currentDay) % 7;

    // If the weekday is the same day check time difference
    if (daysUntilNext === 0) {
        // Calculate time difference
        const currentHour = today.getHours();
        const currentMinute = today.getMinutes();
        const scheduleHour = parseInt(time.split(':')[0]);
        const scheduleMinute = parseInt(time.split(':')[1]);

        // Calculate difference in minutes
        const currentTotalMinutes = currentHour * 60 + currentMinute;
        const scheduleTotalMinutes = scheduleHour * 60 + scheduleMinute;
        const diffMinutes = scheduleTotalMinutes - currentTotalMinutes;

        // If time difference is less than 3 hours, add 7 days
        if (diffMinutes < 180) {
            daysUntilNext = 7;
        }
    }

    today.setDate(today.getDate() + daysUntilNext);

    // Format the date to YYYY-MM-DD HH:MM
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');

    const hours = time.split(':')[0];
    const minutes = time.split(':')[1];

    return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// Posts to be displayed
const posts = ref<PostType[]>([]);

// Populate the posts
if (schedule.advSchedule) {
    // Advanced schedule
    let index = 0;

    Object.keys(schedule.advSchedule).forEach((key, dayIndex) => {
        schedule.advSchedule[key].forEach((value, timeIndex) => {
            posts.value.push({
                id: index.toString(),
                title: `${$gettext('Article')} #${index + 1}`,
                publish_date: getDateOfPublication(key, value),
                status: 'schedule_generate',
                post_link: '',
                keywords: schedule.articles_keywords?.[dayIndex]?.[timeIndex] ?? [],
                dayIndex: dayIndex,
                timeIndex: timeIndex,
            });
            index++;
        });
    });
} else {
    // Basic schedule
    schedule.days.forEach((day, dayIndex) => {
        posts.value.push({
            id: dayIndex.toString(),
            title: `${$gettext('Article')} #${dayIndex + 1}`,
            publish_date: getDateOfPublication(day, schedule.time),
            status: 'schedule_generate',
            post_link: '',
            keywords: schedule.articles_keywords?.[dayIndex]?.[0] ?? [],
            dayIndex: dayIndex,
        });
    });
}

// Update keywords in schedule
const updateKeywordsInSchedule = (keywords: string[], dayIndex: number, timeIndex: number | null) => {
    // Create new keywords
    const newKeywords = schedule.articles_keywords;

    if (timeIndex === null) {
        // Basic schedule
        newKeywords[dayIndex] = [keywords];
    } else {
        // Advanced schedule
        newKeywords[dayIndex][timeIndex] = keywords;
    }

    // Update the schedule
    const newSchedule = {
        ...schedule,
        articles_keywords: newKeywords,
    };

    emit('updateSchedule', newSchedule);
};

// Finish setup
const finishSetup = async () => {
    try {
        // Set loading
        loading.value = true;

        if (!isFirstSchedule) {
            // Add new schedule in Boostsite

            // Set url and body
            const bodyBoostsite = {
                action: 'add',
                schedule: schedule,
            };

            // Save 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}`);
            }
        } else {
            // Create the plugin settings

            // Prepare new settings
            const newSettings = {
                ...config.settings,
                schedules: [schedule],
            };

            // Body
            const bodyWP = {
                settings: newSettings,
                update_boostsite: true,
            };

            // Call the WordPress Rest API to save schedule
            const responseWP = await Axios.post(config.rest.endpoints.settings, bodyWP);

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

        // Add schedule to store
        addSchedule(schedule);

        addNotification({
            message: $gettext('Succefully added new schedule!'),
            type: 'success',
        });

        addNotification(
            {
                message: $gettext(
                    'Your articles are being generated in the background! Please wait a few minutes and refresh the page.'
                ),
                type: 'success',
            },
            60
        );

        // Refresh the page
        setTimeout(() => {
            router.go(0);
        }, 1000);
    } catch (error) {
        console.error('Error saving schedule:', error);

        addNotification({
            message: $gettext('There was an error with saving your schedule!'),
            type: 'danger',
        });
    } finally {
        // Set loading
        loading.value = false;
    }
};

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

<template>
    <div>
        <!-- Messages -->
        <div class="mt-20 flex flex-col items-center gap-4" v-if="!isAccountFree">
            <Message
                :message="
                    $gettext(
                        'Keywords are assigned to a specific article and won\'t be reused for generating future articles in this schedule.'
                    )
                "
                type="info"
                size="large"
                :show-icon="true"
            />

            <Message
                :message="
                    $gettext(
                        'Your articles will be generated in the background. Please check back and refresh the page to see them.'
                    )
                "
                type="info"
                size="large"
                :show-icon="true"
            />
        </div>

        <!-- Posts table -->
        <div class="max-w-[90vw] mx-auto mt-7 md:mt-15">
            <PostsTable
                :loading="false"
                :posts
                type="compact"
                @update-keywords="(keywords: string[], dayIndex: number, timeIndex: number) => updateKeywordsInSchedule(keywords, dayIndex, timeIndex)"
            />
        </div>

        <div class="max-w-[300px] w-full mx-auto my-6 md:mt-10 mb-12 md:mb-20">
            <!-- Button -->
            <Button
                class="w-full"
                :text="isAccountFree ? $gettext('Generate article') : $gettext('Generate articles')"
                size="large"
                @click.prevent="finishSetup"
                :loading
            />

            <!-- Go back -->
            <div class="text-center mt-4">
                <Button
                    :text="$gettext('back to Settings')"
                    size="small"
                    :has-background="false"
                    type="secondary"
                    icon-position="left"
                    @click.prevent="emit('previousStep')"
                >
                    <IconArrowLeft />
                </Button>
            </div>
        </div>

        <!-- Card -->
        <div class="max-w-[520px] mx-auto" v-if="isAccountFree">
            <Card
                :image-url="`${config.plugin_url}/public/images/first-schedule.png`"
                :image-alt="$gettext('Upgrade to premium plan')"
            >
                <p class="text-info-900">
                    {{ $gettext('On trial you can generate and publish only one article.') }}
                    <br />
                    <a href="#" class="underline underline-offset-[3px]" @click.prevent="router.push('/upgrade')">
                        {{ $gettext('Upgrade') }}
                    </a>
                    {{ $gettext('to paid plan to publish more of them.') }}
                </p>
            </Card>
        </div>
    </div>
</template>

<style scoped></style>
