<script lang="ts" setup>
// import

import useGetProduct from "~/composables/api/product/useGetProduct";
import type { ProductVariantProvideType } from "~/pages/product/[id].vue";
import useAddCartItem from "~/composables/api/orders/useAddCartItem";
import { useAuth } from "~/composables/api/auth/useAuth";
import useSaveProduct from "~/composables/api/product/useSaveProduct";
import { QUERY_KEYS } from "~/constants";

// state

const route = useRoute();
const id = route.params.id as string | undefined;

const { token } = useAuth();
const { $queryClient: queryClient } = useNuxtApp();

const { data: product, refetch: refetchProduct, isFetching: isFetchingPending } = useGetProduct(id);
const { mutateAsync: addCartItem, isPending: isAddCartItemPending } = useAddCartItem();
const { mutateAsync: saveProduct, isPending: isSaveProductPending } = useSaveProduct();

const selectedVariantId = ref(product.value!.variants[0].id);
const selectedQuantity = ref(1);
const selectedSlide = ref(product.value!.variants[0].images[0].id);

const selectedColor = ref(product.value!.colors[0]);

// provide / inject

const { selectedVariant, changeSelectedVariant } = inject("productVariant") as ProductVariantProvideType;

// method

const addItemToCart = async () => {
    await addCartItem({
        id: selectedVariant.value!.id,
        quantity: selectedQuantity.value,
    });
    await refetchProduct();
};

const saveProductHandler = async () => {
    await saveProduct({ product_slug: product.value!.slug });
    await queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.product] });
};

// watch

watch([selectedVariantId, product], ([selectedVariantId, product]) => {
    const newVariant = product!.variants.find((variant) => variant.id === selectedVariantId)!;
    changeSelectedVariant(newVariant);
});

watch(
    () => selectedColor.value,
    (newValue) => {
        const filteredVariants = product.value!.variants.filter((v) => v.color === newValue);
        selectedVariantId.value = filteredVariants[0].id;
        selectedVariant.value = filteredVariants[0];
    },
    {
        immediate: true,
    }
);

watch(
    () => selectedVariant.value!,
    (newValue) => {
        selectedQuantity.value = 1;
        selectedSlide.value = newValue.images[0].id;
    },
    {
        immediate: true,
    }
);
</script>

<template>
    <div class="flex max-lg:flex-col lg:gap-12 xl:gap-16 container pt-[5rem] pb-28">
        <div class="flex flex-col gap-3 lg:hidden">
            <div class="flex items-center justify-between w-full">
                <NuxtLink
                    to="#"
                    class="typo-label-sm"
                >
                    {{ product!.category.name }}
                </NuxtLink>
                <button
                    @click="saveProductHandler"
                    :disabled="isSaveProductPending || isFetchingPending || !token"
                    class="size-10 bg-slate-50 border-slate-200 border rounded-lg flex-center"
                >
                    <Icon
                        v-if="isSaveProductPending || isFetchingPending"
                        name="ci:svg-spinners-180-ring-with-bg"
                    />

                    <Icon
                        v-else
                        :class="product?.added_to_favorites ? '**:fill-blue-400' : ''"
                        :name="product?.added_to_favorites ? 'bi-bookmark-fill' : 'ci:bi-bookmark'"
                    />
                </button>
            </div>
            <h1 class="typo-h-6 xs:typo-h-5 sm:typo-h-4 lg:typo-h-2">
                {{ product!.name }}
            </h1>
            <div class="flex w-full items-center justify-between h-[85px]">
                <div class="flex items-end gap-4">
                    <div class="flex flex-col gap-2">
                        <span
                            v-if="selectedVariant!.discount > 0"
                            class="typo-p-md sm:typo-p-lg relative flex-center w-fit"
                            :class="'after:w-full after:h-[2px] after:bg-black after:absolute'"
                        >
                            {{ selectedVariant!.price }}
                        </span>
                        <span class="typo-p-md sm:typo-p-2xl relative flex-center w-fit font-medium">
                            {{
                                selectedVariant!.discount > 0
                                    ? selectedVariant!.price_after_discount
                                    : selectedVariant!.price
                            }}
                        </span>
                    </div>
                    <div
                        v-if="selectedVariant!.discount > 0"
                        class="text-white bg-blue-500 mb-1 px-3 sm:px-4 py-1.5 sm:py-2 text-xs rounded-full flex items-center gap-1"
                    >
                        <Icon
                            name="material-symbols:percent"
                            class="size-3.5 sm:size-4"
                        />
                        {{ selectedVariant!.discount }}
                        <span class="max-sm:hidden"> تخفیف درصد </span>
                    </div>
                </div>
                <Rating :rate="3" />
            </div>
        </div>
        <Slider
            class="w-full lg:w-1/2 lg:max-w-[620px]"
            v-model:selectedSlide="selectedSlide"
            :slides="selectedVariant!.images"
        />
        <div class="lg:w-1/2 flex flex-col gap-3 mt-12">
            <div class="flex items-center justify-between w-full max-lg:hidden">
                <NuxtLink
                    to="#"
                    class="typo-label-sm"
                >
                    {{ product!.category.name }}
                </NuxtLink>
                <button
                    @click="saveProductHandler"
                    :disabled="isSaveProductPending || isFetchingPending || !token"
                    class="size-10 bg-slate-50 border-slate-200 border rounded-lg flex-center"
                >
                    <Icon
                        v-if="isSaveProductPending || isFetchingPending"
                        name="ci:svg-spinners-180-ring-with-bg"
                    />

                    <Icon
                        v-else
                        :class="product?.added_to_favorites ? '**:fill-blue-400' : ''"
                        :name="product?.added_to_favorites ? 'bi-bookmark-fill' : 'ci:bi-bookmark'"
                    />
                </button>
            </div>
            <h1 class="typo-h-4 xl:typo-h-3 max-lg:hidden">
                {{ product!.name }}
            </h1>
            <div class="flex w-full items-center justify-between h-[85px] max-lg:hidden">
                <div class="flex items-end gap-4">
                    <div class="flex flex-col gap-2">
                        <span
                            v-if="selectedVariant!.discount > 0"
                            class="typo-p-lg relative flex-center w-fit"
                            :class="'after:w-full after:h-[2px] after:bg-black after:absolute'"
                        >
                            {{ selectedVariant!.price }}
                        </span>
                        <span class="typo-p-2xl relative flex-center w-fit font-medium">
                            {{
                                selectedVariant!.discount > 0
                                    ? selectedVariant!.price_after_discount
                                    : selectedVariant!.price
                            }}
                        </span>
                    </div>
                    <div
                        v-if="selectedVariant!.discount > 0"
                        class="text-white bg-blue-500 mb-1 px-4 py-2 text-xs rounded-full flex items-center gap-1"
                    >
                        <Icon
                            name="material-symbols:percent"
                            class="size-4"
                        />
                        {{ selectedVariant!.discount }}
                        <span class="max-sm:hidden">درصد</span>
                        تخفیف
                    </div>

                    <Rating
                        :rate="3"
                        class="sm:hidden"
                    />
                </div>

                <Rating
                    :rate="3"
                    class="max-sm:hidden"
                />
            </div>

            <ProductDescription
                class="max-lg:hidden"
                :description="product!.description"
            />

            <div class="flex items-center gap-4">
                <span class="typo-md sm:typo-p-lg"> تنوع رنگی : </span>
                <div class="flex items-center gap-4 py-4">
                    <ColorCircle
                        v-for="color in product!.colors"
                        :key="color"
                        @click="selectedColor = color"
                        selectable
                        :selected="selectedColor === color"
                        :style="{ backgroundColor: color }"
                        class="cursor-pointer"
                    />
                </div>
            </div>

            <div class="flex items-center gap-6 flex-wrap">
                <ProductVariant
                    @click="selectedVariantId = variant.id"
                    v-for="variant in product!.variants.filter(p => p.color === selectedColor)"
                    :key="variant.id"
                    :variantDetail="variant"
                    :isSelected="selectedVariantId === variant.id"
                />
            </div>

            <div class="w-full flex flex-col gap-6 mt-10">
                <RemainQuantity
                    v-if="selectedVariant!.in_stock > 0"
                    :showSlider="selectedVariant!.cart_quantity === 0"
                    :maxQuantity="selectedVariant!.in_stock"
                    :quantity="selectedQuantity"
                />

                <div class="w-full flex gap-3">
                    <template v-if="selectedVariant!.in_stock > 0">
                        <template v-if="token">
                            <Button
                                v-if="selectedVariant!.cart_quantity === 0"
                                @click="addItemToCart"
                                :loading="isAddCartItemPending"
                                :disabled="isAddCartItemPending"
                                class="w-full rounded-full max-sm:h-[48px]"
                                end-icon="ci:plus"
                            >
                                افزودن به سبد خرید
                            </Button>
                            <NuxtLink
                                v-else
                                to="/cart"
                                class="w-full"
                            >
                                <Button
                                    class="w-full rounded-full h-full max-sm:h-[48px]"
                                    end-icon="ci:cart"
                                >
                                    مشاهده در سبد خرید
                                </Button>
                            </NuxtLink>
                        </template>
                        <NuxtLink
                            v-else
                            :to="{ name: 'signin', query: { cb_url: route.path } }"
                            class="w-full"
                        >
                            <Button
                                class="w-full rounded-full h-full max-sm:h-[48px]"
                                end-icon="ci:user"
                            >
                                ابتدا وارد شوید
                            </Button>
                        </NuxtLink>
                    </template>

                    <Button
                        v-else
                        class="w-full !cursor-default rounded-full h-full max-sm:h-[48px]"
                        end-icon="ci:cart"
                    >
                        اتمام موجودی
                    </Button>

                    <QuantityCounter
                        v-if="selectedVariant!.in_stock > 0 && selectedVariant!.cart_quantity === 0"
                        :disable="isAddCartItemPending"
                        v-model="selectedQuantity"
                        :max="selectedVariant!.in_stock"
                    />
                    <UpdateQuantity v-else-if="selectedVariant!.in_stock > 0" />
                </div>

                <div
                    class="flex items-center gap-4"
                    v-if="selectedVariant!.cart_quantity === 0"
                >
                    <NuxtLink
                        v-if="selectedVariant?.special_discount_amount"
                        :to="token ? selectedVariant.special_discount_link : ''"
                        class="w-full"
                    >
                        <Button
                            variant="secondary"
                            class="w-full rounded-full h-full max-sm:h-[48px]"
                            end-icon="ci:bi-percent"
                        >
                            {{ selectedVariant?.special_discount_amount }}
                            تخفیف بگیر
                        </Button>
                    </NuxtLink>
                    <!-- <Button
                        variant="secondary"
                        class="w-full rounded-full h-full max-sm:h-[48px]"
                        end-icon="ci:bi-person-check"
                    >
                        پورسانت بگیر
                    </Button> -->
                </div>

                <InfoCard />

                <Share />
            </div>

            <ProductDescription
                class="lg:hidden"
                :description="product!.description"
            />
        </div>
    </div>
</template>
