<template>
    <ion-page>
        <ion-content :fullscreen="true" ref="content">
            <div ref="el" class="w-full h-full">
                <PlayView v-if="!episodes.length" />
                <VueSwiper
                    v-else
                    class="w-full h-full"
                    virtual
                    direction="vertical"
                    :initialSlide="0"
                    :slides-per-view="1"
                    :space-between="0"
                    :pagination="true"
                    :autoplay="false"
                    @swiper="onSwiper"
                    :modules="[
                        Navigation,
                        Pagination,
                        Scrollbar,
                        A11y,
                        Virtual,
                    ]"
                    @slide-change="onSlideChange"
                >
                    <swiper-slide
                        v-for="(item, n) in episodes"
                        :key="item.id"
                        class="w-full h-full"
                        :virtualIndex="item.id"
                    >
                        <PlayView
                            :active="n === activeSlide"
                            :series="series"
                            :episode="item"
                            :episodes="episodes"
                            :saved="saved"
                            @save="save"
                            @choose-episode="onChooseEpisode"
                            @ended="next"
                            @pay="showPayModal = true"
                        />
                    </swiper-slide>
                </VueSwiper>
            </div>

            <ion-modal
                ref="modal"
                class="pay-modal"
                :is-open="showPayModal"
                :initial-breakpoint="1"
                :breakpoints="[0, 1]"
                @ionModalDidDismiss="showPayModal = false"
            >
                <ion-content>
                    <div class="divide-y divide-neutral-600 text-white">
                        <div class="mb-6">
                            <div
                                class="mt-6 text-center text-sm text-prim text-opacity-80"
                            >
                                You haven't unlocked this episode yet
                            </div>
                            <div class="text-center text-xl mt-2 font-bold">
                                Join the Membership
                            </div>
                            <div class="text-center text-sm mt-1 px-4">
                                unlock and watch all our videos without any
                                limit
                            </div>
                        </div>
                        <div class="flex space-x-4 pt-6 px-4">
                            <div
                                v-for="(item, n) in plans"
                                :key="n"
                                class="h-44 bg-neutral-700 flex-1 rounded-lg flex flex-col items-center border-neutral-500 border-2 overflow-hidden relative"
                                :class="{ '!border-prim': selectedPlan === n }"
                                @click="selectedPlan = n"
                            >
                                <div
                                    class="absolute top-0 left-0 bg-prim rounded-br-lg text-xs px-2 py-1"
                                    v-if="n === 0"
                                >
                                    Exclusive
                                </div>
                                <div class="mt-8 text-xl font-bold flex-1">
                                    {{ item.title }}
                                </div>
                                <div class="flex-1">
                                    <div
                                        class="bg-prim bg-opacity-30 rounded-full px-3 py-1 text-opacity-50 text-sm"
                                    >
                                        {{ item.desc }}
                                    </div>
                                </div>
                                <div
                                    class="h-8 bg-neutral-500 self-stretch text-base font-bold flex items-center justify-center"
                                    :class="{ 'bg-prim': selectedPlan === n }"
                                >
                                    <ion-label color="">
                                        ${{ item.price }}
                                    </ion-label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <IonButton
                        color="tertiary"
                        expand="block"
                        class="mx-4 mt-8 font-bold"
                        @click="onClickPay"
                    >
                        ${{ plans[selectedPlan].price }} Pay Now
                    </IonButton>
                </ion-content>
            </ion-modal>

            <IonModal :isOpen="showCheckoutModal">
                <IonHeader>
                    <IonToolbar>
                        <IonButtons slot="secondary">
                            <IonButton @click="showCheckoutModal = false">
                                <IonIcon :icon="chevronBack" />
                            </IonButton>
                        </IonButtons>
                        <IonTitle>
                            <IonLabel>Checkout</IonLabel>
                        </IonTitle>
                    </IonToolbar>
                </IonHeader>
                <IonContent>
                    <iframe
                        class="h-full w-full border-none"
                        :src="payUrl"
                    ></iframe>
                </IonContent>
            </IonModal>
        </ion-content>
    </ion-page>
</template>
<script setup lang="ts">
import {
    IonPage,
    IonContent,
    useIonRouter,
    IonModal,
    IonHeader,
    IonButtons,
    IonButton,
    IonToolbar,
    IonLabel,
    IonBackButton,
    IonTitle,
    IonIcon,
} from "@ionic/vue";
import { Swiper as VueSwiper, SwiperSlide } from "swiper/vue";
import { Swiper } from "swiper";
import {
    Navigation,
    Pagination,
    Scrollbar,
    A11y,
    Virtual,
} from "swiper/modules";
import PlayView from "@/components/PlayView.vue";
import { nextTick, onMounted, reactive, ref } from "vue";
import { useElementBounding } from "@vueuse/core";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import { close, chevronBack } from "ionicons/icons";
import toast from "@/plugins/toast";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import emitter from "@/events";

const { user } = storeToRefs(useUserStore());
const el = ref<HTMLElement | null>(null);
const { x, y, top, right, bottom, left, width, height } =
    useElementBounding(el);

const swiper = ref<Swiper | null>(null);
const onSwiper = (sw: Swiper) => {
    window.swiper = swiper.value = sw;
};
const activeSlide = ref(0);

const route = useRoute();
const router = useIonRouter();
const seriesId = route.params.id;
const series = ref<any>(null);
const episodes = ref<any[]>([]);

onMounted(() => {
    http.get(`/series/${seriesId}`).then((res) => {
        series.value = res;
        http.get(`/episodes`, {
            seriesId: seriesId,
            order: "episodeNum",
            pageSize: 1000,
        }).then((res) => {
            episodes.value = res.data;
            nextTick(() => {
                swiper.value?.update();
            });
        });
    });
    http.get(`/collections/${seriesId}`).then((res) => {
        saved.value = true;
    });
});

function onSlideChange(e: any) {
    activeSlide.value = e.activeIndex;
}

function onChooseEpisode(n: number) {
    swiper.value?.slideTo(n, 0);
}

const saved = ref(false);

function save() {
    if (saved.value) {
        http.delete(`/collections/${seriesId}`).then(() => {
            saved.value = false;
        });
    } else {
        http.post(`/collections`, {
            seriesId: seriesId,
            curEpId: episodes.value[activeSlide.value]?.id,
        }).then(() => {
            saved.value = true;
        });
    }
}

function next() {
    if (activeSlide.value < episodes.value.length - 1) {
        swiper.value?.slideTo(activeSlide.value + 1);
    }
}
const showPayModal = ref(false);
const plans = [
    {
        title: "7 Days",
        desc: "Unlimited",
        price: 0.99,
        value: 7,
    },
    {
        title: "1 Month",
        desc: "Unlimited",
        price: 19.99,
        value: 30,
    },
    {
        title: "3 Months",
        desc: "Unlimited",
        price: 49.99,
        value: 90,
    },
];
const selectedPlan = ref(0);
const showCheckoutModal = ref(false);
window.addEventListener("message", async (event) => {
    console.log(event);
    if (event.data === "success") {
        await http.post("/memberships", {
            userId: user.value!.id,
            expireAt: new Date(
                new Date().getTime() +
                    plans[selectedPlan.value].value * 24 * 60 * 60 * 1000
            ),
        });
        toast("Payment successful", {
            type: "success",
        });
        showCheckoutModal.value = false;
        emitter.emit('payment-success')
    } else if (event.data === "fail") {
        toast("Payment failed", {
            type: "error",
        });
        showCheckoutModal.value = false;
    }
});

const payUrl = ref("http://192.168.50.202:5174/stripe-checkout/");
function onClickPay() {
    showPayModal.value = false;
    setTimeout(() => {
        payUrl.value = "http://192.168.50.202:5174/stripe-checkout/";
        showCheckoutModal.value = true;
    }, 200);
}
</script>
<style lang="less" scoped>
.pay-modal {
    --height: 50vh;
}
</style>
