<!-- Subscription settings tab -->
<script setup lang="ts">
import Card from '../layout/Card.vue';
import Button from '../base/Button.vue';
import Popup from '../layout/Popup.vue';
import { AppConfigType, SubscriptionDetailsType } from '~src/admin/types';
import { inject, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useNotificationStore } from '~src/admin/stores/useNotificationStore';
import { useGettext } from 'vue3-gettext';
import Axios from '~src/shared/axios';
import IconWarning from '../icons/IconWarning.vue';
import SubscriptionEnd from './SubscriptionEnd.vue';

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

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

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

// Router
const router = useRouter();

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

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

// Get subscription details
const subscriptionDetails = ref<SubscriptionDetailsType>();

// Get subscription details
onMounted(async () => {
    try {
        // Call the WordPress Rest API to get subscription details
        const response = await Axios.get(`${config.rest.endpoints.boostsite}/subscription_details`);

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

        // Update the subscription details
        if (response?.data?.data) {
			const responseData = response.data.data[0];

			// Parse the data
            subscriptionDetails.value = {
				status: responseData.status,
				planType: responseData.planType,
				price: Number(responseData.price) / 100,
				nextPayment: responseData.nextPayment ? formatDate(new Date(responseData.nextPayment * 1000)) : null,
				lastPayment: responseData.lastPayment ? formatDate(new Date(responseData.lastPayment * 1000)) : null,
				planInterval: responseData.planInterval,
			}
        }
    } catch (error) {
        console.error('Error while getting subscrpition details:', error);

        addNotification({
            message: $gettext('There was an error while getting the subscription details!'),
            type: 'danger',
        });
    }
});

// Loading
const loading = ref(false);

// Cancel subscription
const cancelSubscription = async () => {
    try {
        // Loading
        loading.value = true;

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

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

        // Close the popup
        cancelPopup.value.closePopup();

        // Show success notification
        addNotification({
            message: $gettext('Subscription has been successfully canceled!'),
            type: 'success',
        });

        // Refresh the page
        setTimeout(() => {
            router.go(0);
        }, 2000);
    } catch (error) {
        console.error('Error while canceling subscription:', error);

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

// Format price
const formatPrice = (price: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price);
};

// Format date
const formatDate = (date : Date) => {
    if (!date) return '';
    return date.toLocaleDateString('en-US', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
    });
};
</script>

<template>
    <!-- Card -->
    <div class="max-md:mx-auto max-w-[370px] w-full" v-if="isAccountFree">
        <Card
            :image-url="`${config.plugin_url}/public/images/settings.png`"
            :image-alt="$gettext('Upgrade to premium plan')"
            type="vertical"
        >
            <div class="flex flex-col gap-6">
                <div>
                    <p class="text-info-900 mb-1.5">{{ $gettext("With premium plan you'll get:") }}</p>
                    <ul class="text-info-900 list-disc pl-4">
                        <li>{{ $gettext('unlimited subjects & schedules') }}</li>
                        <li>
                            {{
                                $gettext(
                                    'up to 35 articles generated per week (with option to buy additional articles when needed)'
                                )
                            }}
                        </li>
                        <li>{{ $gettext('advanced scheduling') }}</li>
                        <li>{{ $gettext('ability to add key words to every article') }}</li>
                    </ul>
                </div>

                <Button :text="$gettext('Upgrade')" size="large" @click.prevent="router.push('/upgrade')" />
            </div>
        </Card>
    </div>
    <!-- Card -->

    <div v-else-if="!isAccountFree && subscriptionDetails">
        <!-- Subscription details -->
        <div class="p-5 bg-neutral-50 border border-neutral-500 rounded-lg max-w-[450px]">
            <!-- Subscription info -->
            <p class="text-primary-500 mb-5 text-base">{{ subscriptionDetails.planType }}</p>

            <div class="flex justify-between items-center mb-5">
                <p class="font-bold text-base">{{ $gettext('Subtotal') }}</p>

                <p class="text-base">{{ formatPrice(subscriptionDetails.price) }}</p>
            </div>

            <div class="flex justify-between items-center mb-5">
                <p class="font-bold text-base">{{ $gettext('Tax') }}</p>

                <p class="text-base-200 text-base">{{ $gettext('Enter address to calculate') }}</p>
            </div>

            <!-- Total -->
            <div class="flex justify-between items-center py-6 md:py-8 border-y border-y-neutral-900">
                <p class="font-bold text-base">{{ $gettext('Total') }}</p>

                <p class="font-bold text-xl md:text-2xl leading-xl">{{ formatPrice(subscriptionDetails.price) }}</p>
            </div>

            <!-- Next payment -->
            <div v-if="subscriptionDetails.status === 'active'">
                <p class="text-base-200 mt-1.5 text-base">
                    {{ $gettext('Next payment on') }} {{ subscriptionDetails.nextPayment }}
                </p>
            </div>

            <!-- Renew subscription -->
            <div v-else-if="subscriptionDetails.status === 'canceled'">
                <Button class="mt-5" :text="$gettext('Renew subscription')" type="primary" @click.prevent="" />
            </div>
        </div>
        <!-- Subscription details -->

        <!-- Cancel subscription -->
        <Button
            class="p-0 mt-3"
            :text="$gettext('Cancel subscription')"
            type="secondary"
            :has-background="false"
            @click.prevent="cancelPopup.openPopup()"
            v-if="subscriptionDetails.status === 'active'"
        />
    </div>

    <!-- Cancel popup -->
    <Popup
        ref="cancelPopup"
        :cancel-button-text="$gettext('Nevermind')"
        :confirm-button-text="$gettext('Cancel subscription')"
        confirm-button-type="danger"
        size="small"
        :loading="loading"
        @popup-confirm="cancelSubscription"
        v-if="!isAccountFree && subscriptionDetails"
    >
        <div class="text-center">
            <IconWarning class="mb-4 mx-auto" />
            <h2 class="text-[20px] leading-lg font-bold">{{ $gettext('Are you sure?') }}</h2>

            <p class="text-base">{{ $gettext('If you cancel subscription, you will lose:') }}</p>
            <ul class="flex flex-col items-center list-disc text-base">
                <li class="m-0">{{ $gettext('ability to automate your content publishing process,') }}</li>
                <li class="m-0">{{ config.settings.schedules.length }} {{ $gettext('created schedules,') }}</li>
                <li class="m-0">{{ $gettext('35 articles generated weekly, with no hassle') }}</li>
            </ul>
        </div>
    </Popup>

    <!-- Subscription end banner -->
    <Teleport to="#subscription-end" v-if="subscriptionDetails && subscriptionDetails.status === 'canceled'">
        <SubscriptionEnd :end-time="subscriptionDetails.nextPayment" />
    </Teleport>
</template>

<style scoped></style>
