from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.utils import timezone
from datetime import timedelta
import stripe
import json

from .models import SubscriptionPlan, Subscription, Payment

# Initialize Stripe
stripe.api_key = settings.STRIPE_SECRET_KEY


@login_required
def subscription_page(request):
    """Display subscription plans"""
    plans = SubscriptionPlan.objects.filter(is_active=True).order_by('price')
    
    # Get user's current subscription if any
    current_subscription = Subscription.objects.filter(
        user=request.user, 
        status='active'
    ).first()
    
    context = {
        'plans': plans,
        'current_subscription': current_subscription,
        'stripe_publishable_key': settings.STRIPE_PUBLISHABLE_KEY,
    }
    return render(request, 'subscription.html', context)


@login_required
@require_http_methods(["POST"])
def create_checkout_session(request):
    """Create a Stripe checkout session"""
    try:
        data = json.loads(request.body)
        plan_id = data.get('plan_id')
        
        plan = get_object_or_404(SubscriptionPlan, id=plan_id, is_active=True)
        
        # Create or get Stripe customer
        customer = None
        existing_subscription = Subscription.objects.filter(
            user=request.user,
            stripe_customer_id__isnull=False
        ).first()
        
        if existing_subscription and existing_subscription.stripe_customer_id:
            customer_id = existing_subscription.stripe_customer_id
        else:
            # Create new customer
            customer = stripe.Customer.create(
                email=request.user.email,
                name=request.user.get_full_name() or request.user.username,
                metadata={
                    'user_id': request.user.id,
                    'username': request.user.username
                }
            )
            customer_id = customer.id
        
        # Create checkout session
        checkout_session = stripe.checkout.Session.create(
            customer=customer_id,
            payment_method_types=['card'],
            line_items=[{
                'price_data': {
                    'currency': 'usd',
                    'unit_amount': int(plan.price * 100),  # Convert to cents
                    'product_data': {
                        'name': plan.name,
                        'description': f'{plan.get_plan_type_display()} - Yearly Subscription',
                    },
                },
                'quantity': 1,
            }],
            mode='payment',
            success_url=request.build_absolute_uri('/subscription/success/') + '?session_id={CHECKOUT_SESSION_ID}',
            cancel_url=request.build_absolute_uri('/subscription/'),
            metadata={
                'user_id': request.user.id,
                'plan_id': plan.id,
            }
        )
        
        # Create pending subscription
        subscription = Subscription.objects.create(
            user=request.user,
            plan=plan,
            status='pending',
            stripe_customer_id=customer_id,
        )
        
        # Create pending payment
        Payment.objects.create(
            user=request.user,
            subscription=subscription,
            amount=plan.price,
            status='pending',
            stripe_payment_intent_id=checkout_session.id,
        )
        
        return JsonResponse({
            'success': True,
            'checkout_url': checkout_session.url
        })
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=400)


@login_required
def subscription_success(request):
    """Handle successful subscription payment"""
    session_id = request.GET.get('session_id')
    
    if not session_id:
        messages.error(request, 'Invalid session.')
        return redirect('subscription')
    
    try:
        # Retrieve the session from Stripe
        session = stripe.checkout.Session.retrieve(session_id)
        
        if session.payment_status == 'paid':
            # Find the pending subscription
            subscription = Subscription.objects.filter(
                user=request.user,
                status='pending'
            ).order_by('-created_at').first()
            
            if subscription:
                # Activate subscription
                subscription.status = 'active'
                subscription.start_date = timezone.now()
                subscription.end_date = timezone.now() + timedelta(days=subscription.plan.duration_days)
                subscription.stripe_subscription_id = session.id
                subscription.save()
                
                # Update payment
                payment = Payment.objects.filter(
                    subscription=subscription,
                    status='pending'
                ).first()
                
                if payment:
                    payment.status = 'completed'
                    payment.stripe_charge_id = session.payment_intent
                    payment.save()
                
                messages.success(request, f'Successfully subscribed to {subscription.plan.name}!')
            else:
                messages.warning(request, 'Subscription not found, but payment was successful.')
        else:
            messages.error(request, 'Payment was not completed.')
            
    except Exception as e:
        messages.error(request, f'Error processing subscription: {str(e)}')
    
    return redirect('/')


@login_required
def cancel_subscription(request, subscription_id):
    """Cancel a subscription"""
    subscription = get_object_or_404(
        Subscription, 
        id=subscription_id, 
        user=request.user
    )
    
    if subscription.status == 'active':
        subscription.status = 'cancelled'
        subscription.auto_renew = False
        subscription.save()
        messages.success(request, 'Your subscription has been cancelled.')
    else:
        messages.error(request, 'This subscription is not active.')
    
    return redirect('subscription')


@csrf_exempt
@require_http_methods(["POST"])
def stripe_webhook(request):
    """Handle Stripe webhooks"""
    payload = request.body
    sig_header = request.META.get('HTTP_STRIPE_SIGNATURE')
    
    # Note: In production, you should set up webhook signing secret
    # webhook_secret = settings.STRIPE_WEBHOOK_SECRET
    
    try:
        event = json.loads(payload)
        
        # Handle the event
        if event['type'] == 'checkout.session.completed':
            session = event['data']['object']
            # Handle successful payment
            pass
        elif event['type'] == 'payment_intent.succeeded':
            payment_intent = event['data']['object']
            # Handle successful payment
            pass
        elif event['type'] == 'payment_intent.payment_failed':
            payment_intent = event['data']['object']
            # Handle failed payment
            pass
        
        return JsonResponse({'status': 'success'})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)

