<!--  First schedule site topic view -->
<script setup lang="ts">
import { inject, onMounted, ref } from 'vue';
import Button from '../base/Button.vue';
import TextInput from '../form/TextInput.vue';
import { AppConfigType, ScheduleType } from '~src/admin/types';
import Card from '../layout/Card.vue';
import { useRouter } from 'vue-router';
import Axios from '~src/shared/axios';
import { useNotificationStore } from '~src/admin/stores/useNotificationStore';
import { useGettext } from 'vue3-gettext';

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

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

// Router
const router = useRouter();

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

// Loading
const loading = ref(false);

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

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

// Topic value
const selectedTopic = ref(schedule.topic || '');

// Error handling
const errorMsg = ref('');

// Try to get the topic from the API
onMounted(async () => {
    try {
        // Set loading
        loading.value = true;

        // Call the WordPress Rest API to generate topic
        const response = await Axios.get(`${config.rest.endpoints.boostsite}/generate_topic`);

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

        // Show the generated topic
		if (response?.data?.data?.data) {
			selectedTopic.value = response.data.data.data;
		}
    } catch (error) {
        console.error('Error generating while topic:', error);

        addNotification({
            message: $gettext('There was an error while generating the topic!'),
            type: 'danger',
        });
    } finally {
        // Set loading
        loading.value = false;
    }
});

// Go to next step
const goToNextStep = () => {
    errorMsg.value = '';

    // Topic validation
    if (!selectedTopic.value) {
        errorMsg.value = $gettext('Please provide subject.');
        return;
    }

    // Update the schedule
    const newSchedule = {
        ...schedule,
        topic: selectedTopic.value,
    };

    emit('updateSchedule', newSchedule);

    // Go to next step and update the schedule
    emit('nextStep');
};

// Set texts based on if schedule is first or not
let title = $gettext('What is a topic of your website?');
let subtitle = $gettext('We will use it later to generate articles. You can always change it later in settings.');

if (!isFirstSchedule) {
    title = $gettext('What should articles be about?');
    subtitle = $gettext('Describe the subject of the articles.');
}

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

<template>
    <div class="entry-animation">
        <!-- Intro text -->
        <div class="mt-12 md:mt-20 mb-8 text-center">
            <h1 class="mb-1 text-md font-bold leading-tight">{{ title }}</h1>
            <p class="text-base-200">
                {{ subtitle }}
            </p>
        </div>
        <!-- Intro text -->

        <div class="mx-auto mb-12 md:mb-20 w-full max-w-[300px]">
            <!-- Topic input -->
            <TextInput
                class="mb-6 md:mb-10"
                :placeholder="$gettext('e.g. furniture')"
                v-model="selectedTopic"
                :error-msg="errorMsg"
                :disabled="loading"
            />

            <!-- Button -->
            <Button class="w-full" :text="$gettext('Next')" size="large" @click.prevent="goToNextStep" :loading />
        </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('Need more topics or key words?') }}
                    <br />
                    <a href="#" class="underline underline-offset-[3px]" @click.prevent="() => router.push('/upgrade')">
                        {{ $gettext('Upgrade') }}
                    </a>
                    {{ $gettext('to our paid plan to unlock powerful features.') }}
                </p>
            </Card>
        </div>
    </div>
</template>

<style lang="scss" scoped></style>
