from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import PaymentTransaction
from invoice_discounting.models import Invoice
from decimal import Decimal
import uuid

@login_required
def initiate_payment(request, invoice_id):
    """Initiate payment for an invoice"""
    invoice = get_object_or_404(Invoice, id=invoice_id)
    
    if request.method == 'POST':
        payment_method = request.POST.get('payment_method')
        
        # Create transaction record
        transaction = PaymentTransaction.objects.create(
            transaction_id=f"TXN{uuid.uuid4().hex[:12].upper()}",
            invoice=invoice,
            amount=invoice.discounting_amount or invoice.invoice_amount,
            payment_method=payment_method,
            customer_name=request.user.get_full_name() or request.user.username,
            customer_email=request.user.email,
            status='PROCESSING'
        )
        
        # Process based on payment method
        if payment_method == 'CARD':
            from .services.stripe_service import StripePaymentService
            service = StripePaymentService()
            result = service.create_payment_intent(
                amount=float(transaction.amount),
                metadata={'transaction_id': transaction.transaction_id}
            )
            
            if result['success']:
                return JsonResponse({
                    'client_secret': result['client_secret'],
                    'transaction_id': transaction.transaction_id
                })
            else:
                transaction.status = 'FAILED'
                transaction.save()
                messages.error(request, f"Payment failed: {result.get('error')}")
        
        elif payment_method == 'YOURCODING':
            from .services.stripe_service import YourCodingPaymentService
            service = YourCodingPaymentService()
            result = service.initiate_payment(
                amount=float(transaction.amount),
                customer_details={
                    'name': transaction.customer_name,
                    'email': transaction.customer_email
                }
            )
            
            if result['success']:
                return redirect(result['payment_url'])
        
        return redirect('payment_status', transaction_id=transaction.transaction_id)
    
    return render(request, 'payments/initiate.html', {
        'invoice': invoice,
        'payment_methods': PaymentTransaction.PAYMENT_METHODS
    })

@login_required
def payment_status(request, transaction_id):
    """Check payment status"""
    transaction = get_object_or_404(PaymentTransaction, transaction_id=transaction_id)
    
    # Update status from gateway if needed
    if transaction.status == 'PROCESSING':
        # Check with payment gateway
        pass
    
    return render(request, 'payments/status.html', {
        'transaction': transaction
    })

@csrf_exempt
def payment_webhook(request):
    """Webhook for payment gateway callbacks"""
    import json
    
    try:
        data = json.loads(request.body)
        
        # Process webhook data
        transaction_id = data.get('transaction_id')
        status = data.get('status')
        
        if transaction_id:
            transaction = PaymentTransaction.objects.get(transaction_id=transaction_id)
            transaction.status = status.upper()
            
            if status.upper() == 'COMPLETED':
                transaction.payment_date = timezone.now()
                
                # Update invoice status
                if transaction.invoice:
                    transaction.invoice.status = 'REPAID'
                    transaction.invoice.save()
            
            transaction.save()
        
        return JsonResponse({'status': 'ok'})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)