
import logging

from django.views import View
from django.conf import settings
from django.http import JsonResponse

from apps.subscriptions.utils import UpgradeSubscription
from apps.accounts.models import User
from apps.accounts.utils import upgrade_subscriber_group
import requests
from apps.accounts.models import User
from apps.subscriptions.models import Subscription, Plan, Payment,PendingSubs
from requests.exceptions import RequestException
from django.views.decorators.csrf import csrf_exempt


logger = logging.getLogger(__file__)

# Create your views here.

def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

class PlanCheckerView(View):
    def post(self, request, *args, **kwargs):
        if is_ajax(request):
            return JsonResponse({'status': 'success', 'message': 'Upgrade is allowed'}) if request.user.subscription.plan.plan_id != request.POST['PlanID'] else JsonResponse({'status': 'error', 'message': 'You cannot upgrade to your current plan'})


class UpgradePlanView(View):
    def post(self, request, *args, **kwargs):
        if is_ajax(request):
            
            # assign user to new plan
            old_plan = None
            if request.user.subscription.plan != None:
                old_plan = request.user.subscription.plan

            # create new payment refered to same user subscription
            
            logger.info(" Create new Payment success! ")
            try:

                payment = Payment.objects.get(subscription=request.user.subscription,is_active=True)
                #upgrade user to the new plan
                new_subscription = Subscription.objects.get(user=request.user)
                new_plan = Plan.objects.get(plan_id=request.POST['PlanID'])
                new_subscription.plan = new_plan
                new_subscription.save()
                logger.info("Plan Upgraded Suceess!")

                
                
                print("Old Plan: ",f'{old_plan.plan_name}_{old_plan.plan_duration}')
                # upgrade mailer lite user status
                if old_plan.plan_name =="Free":
                    upgrade_subscriber_group(
                        email=new_subscription.user.email, #email
                        group=f"{new_plan.plan_name}_{new_plan.plan_duration}",
                        fields={
                            "last_name": new_subscription.user.last_name,
                            "old_plan": f"{old_plan.plan_name} {old_plan.plan_duration}",
                            "new_plan": f"{new_plan.plan_name} {new_plan.plan_duration}" 
                        }
                    )
                else:
                    upgrade_subscriber_group(
                        email=new_subscription.user.email, #email
                        first_name=new_subscription.user.first_name, #first name
                        fields={
                            "last_name": new_subscription.user.last_name,
                            "old_plan": f"{old_plan.plan_name} {old_plan.plan_duration}",
                            "new_plan": f"{new_plan.plan_name} {new_plan.plan_duration}" 
                        },
                        
                    )
                    logger.info("Subscription Updated Success")
                try:

                    upgrade = UpgradeSubscription(CLIENT_ID=settings.PAYPAL_CLIENTID,CLIENT_SECRET=settings.PAYPAL_SECRETID)
                    upgrade.revise(new_plan.plan_id,payment.sub_id)
                except RequestException as ex:
                    pending = PendingSubs()
                    pending.plan_id = new_plan.plan_id
                    pending.payment = payment
                    pending.revise_failed_reason = ex

                # print("Revise: ",upgrade.revise(new_plan.plan_id,payment.sub_id).content)
                # logger.info("Revice Success") 

                return JsonResponse({'status': 'OK', 'message': "Plan Upgraded successfully"})
            except Payment.DoesNotExist:
                return JsonResponse({"status":"error","message":"You have no active payment"})
            

class CreateSubscriptionView(View):
    def post(self, request, *args, **kwargs):
        try: 
            # get user by email
            user = User.objects.get(email=request.POST.get('email')) 
            # condition user != None
            if user != None: 
                # get plan by id
                if 'OrderID' in request.POST and 'plan' in request.session:
                    plan_instance = Plan.objects.get(plan_id=request.session['plan'])
                else:
                    plan_instance = Plan.objects.get(plan_name="Free", plan_duration="Monthly")
                # create a subscription object linked to user
                new_subscription = Subscription()
                new_subscription.plan = plan_instance
                new_subscription.plan = plan_instance
                new_subscription.user = user
                new_subscription.is_active = True # update it by webhook
                new_subscription.paid_status = True # should be a list choie (ACTIVE,SUSPENDED,CALCELED)
                new_subscription.save()  
                
                 # check payment status 
                if 'OrderID' in request.POST:
                    new_payment = Payment()
                    new_payment.transactionID = request.POST.get('OrderID','')
                    new_payment.conversationID = request.POST.get('ConversationID','')
                    new_payment.subscription = new_subscription
                    new_payment.sub_id = request.POST.get('SubscriptionID','')
                    new_payment.is_active = True
                    new_payment.save()
                    # 
                    return JsonResponse({
                        "result": "success",
                        "message": "Subscriptions created successfully with Payement response",
                    })
                # 
                return JsonResponse({
                    "result": "failed",
                    "message": "Subscriptions created successfully without Payement response",
                })
               #  
            else:
                return JsonResponse({
                    "result": "failed",
                    "message": "User not found",
                })
        except Exception as ex:
            return JsonResponse({"result":"error","message":str(ex)})



class SubscriptionCancelView(View):
    """
    Class-based view to handle subscription cancellation via DELETE method.
    """
    
    def delete(self, request, subscription_id=None, *args, **kwargs):
        """
        Handle the DELETE request to cancel a subscription.
        Args:
        - request: Django request object.
        - subscription_id: ID of the subscription to cancel.
        Returns:
        - JsonResponse: Response indicating success or failure.
        """
        # Retrieve the subscription instance
        user = request.user
        try:
            subscription = Subscription.objects.get(user=user)

            # get last active payment 
            payment = Payment.objects.get(subscription=subscription,is_active=True)
            # Deactivate subscription 
            subscription.is_active = False
            subscription.paid_status = False
            subscription.save()

            # Deactivate Payment
            payment.is_active = False
            payment.save()
            return JsonResponse({"status":"success","message":"Subscription Canceled Successfully"},status=204)
        except Exception as ex:
            return JsonResponse({"status":"failed","message":str(ex)})

        # subscription =  UpgradeSubscription(CLIENT_ID=settings.PAYPAL_CLIENTID,CLIENT_SECRET=settings.PAYPAL_SECRETID)

        # response = subscription.cancel(payment.sub_id)
        # if response.status_code != 204:
        #     return JsonResponse({'message': str(response.text)}, status=400)

       

        


    def dispatch(self, request, *args, **kwargs):
        """
        Dispatch method to ensure that only DELETE requests are allowed.
        Args:
        - request: Django request object.
        Returns:
        - Response: Error if method is not DELETE, otherwise continues to view handler.
        """
        if request.method != 'DELETE':
            return JsonResponse({'error': 'Method not allowed. Only DELETE requests are permitted.'}, status=405)
        return super().dispatch(request, *args, **kwargs)