from django.shortcuts import render, get_object_or_404, redirect
from rest_framework.views import APIView, Response
from product.models import ProductModel, SubCategoryModel, MainCategoryModel, ProductVariant
from product.serializers import SubCategorySerializer, DynamicProductSerializer, MainCategorySerializer
from .serializers import *
from .models import *
from rest_framework import status
from django.views import View
from django.db.models import Prefetch
from django.core.cache import cache


class ChangeViewVideo(View):
    def get(self, request, pk):
        videomodel = get_object_or_404(LearnVideoModel, pk=pk)
        videomodel.viewd = not videomodel.viewd
        videomodel.save()
        return redirect('admin:home_learnvideomodel_changelist')


class HomeView(APIView):
    authentication_classes = []
    
    def get(self, request):
        # Check cache first for anonymous users
        cache_key = 'home_view_data_anonymous'
        if not request.user.is_authenticated:
            cached_data = cache.get(cache_key)
            if cached_data:
                return Response(cached_data, status=status.HTTP_200_OK)

        sliders = SliderModel.objects.only('id', 'link', 'title', 'description', 'image', 'video')[:10]
        slider_ser = SliderSerializer(instance=sliders, many=True, context={'request': request})

        main_categories = MainCategoryModel.objects.filter(
            show_in_home=True
        ).prefetch_related('subcategorys')
        main_category_ser = MainCategorySerializer(instance=main_categories, many=True, context={'request': request})

        # Optimize variant prefetching - prefetch all variants, limit applied in serializer
        variant_prefetch = Prefetch(
            'variants',
            ProductVariant.objects.prefetch_related('images').order_by('-discount', 'price')
        )

        # Top seller products
        top_seller_products = ProductModel.objects.filter(
            show_in_top_seller=True
        ).select_related('category', 'shop').prefetch_related(
            variant_prefetch
        ).only('id', 'name', 'image', 'rating', 'slug', 'category', 'shop')[:20]
        top_seller_products_ser = DynamicProductSerializer(
            instance=top_seller_products, 
            many=True, 
            context={'request': request, 'view_type': 'list'}
        )

        # Lot of discount products
        lot_of_discount_products = ProductModel.objects.filter(
            show_in_lot_of_discount=True
        ).select_related('category', 'shop').prefetch_related(
            variant_prefetch
        ).only('id', 'name', 'image', 'rating', 'slug', 'category', 'shop')[:20]
        lot_of_discount_products_ser = DynamicProductSerializer(
            instance=lot_of_discount_products,
            many=True,
            context={'request': request, 'view_type': 'list'}
        )

        # Most viewed products
        most_viewed_products = ProductModel.objects.filter(
            show_in_most_viewed=True
        ).select_related('category', 'shop').prefetch_related(
            variant_prefetch
        ).only('id', 'name', 'image', 'rating', 'slug', 'category', 'shop')[:20]
        most_viewed_products_ser = DynamicProductSerializer(
            instance=most_viewed_products,
            many=True,
            context={'request': request, 'view_type': 'list'}
        )

        # Trends products
        trends_products = ProductModel.objects.filter(
            show_in_trends=True
        ).select_related('category', 'shop').prefetch_related(
            variant_prefetch
        ).only('id', 'name', 'image', 'rating', 'slug', 'category', 'shop')[:20]
        trends_products_ser = DynamicProductSerializer(
            instance=trends_products,
            many=True,
            context={'request': request, 'view_type': 'list'}
        )

        home_image = HomeImageModel.objects.only(
            'id', 'image1', 'image2', 'title1', 'title2', 
            'description1', 'description2', 'link1', 'link2', 
            'video1', 'video2'
        ).first()
        home_image_ser = HomeImageSerializer(instance=home_image, context={'request': request})

        show_cases = ShowCaseSlider.objects.only(
            'id', 'title', 'description', 'image1', 'image2', 'image3', 'background_image'
        )[:10]
        show_cases_ser = ShowCaseSliderSerialzier(instance=show_cases, many=True, context={'request': request})

        response = {
            'sliders': slider_ser.data,
            'main_categories': main_category_ser.data, 
            'products': [],
            'top_seller_products': top_seller_products_ser.data,
            'lot_of_discount_products': lot_of_discount_products_ser.data,
            'most_viewed_products': most_viewed_products_ser.data,
            'trends_products': trends_products_ser.data,
            'difreance_section': home_image_ser.data,
            'show_case_slider': show_cases_ser.data
        }

        # Cache for anonymous users only (avoid issues with user-specific data)
        if not request.user.is_authenticated:
            cache.set(cache_key, response, 60 * 5)  # 5 minutes cache

        return Response(response, status=status.HTTP_200_OK)