from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, get_user_model, login, logout
from django.db import transaction
from .models import Service, Course, Portfolio, Gallery, Blog, Testimonial, Application, PaymentItem, Payment
from .forms import ContactForm, ApplicationForm, ApplicantProfileForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.template.loader import render_to_string
from core.services.remita_invoice import RemitaInvoice
from core.services.remita_verify import RemitaVerify
from django.conf import settings
import json
from django.urls import reverse
from django.db.models import Sum, Value, DecimalField
from django.db.models.functions import Coalesce
from decimal import Decimal

# from accounts.models import User



User = get_user_model()

def home(request):
    context = {
        "services": Service.objects.filter(is_active=True).order_by("display_order")[:6],
        "courses": Course.objects.filter(is_active=True)[:6],
        # "projects": Portfolio.objects.filter(is_active=True)[:6],
        "testimonials": Testimonial.objects.filter(is_active=True)[:6],
        "blogs": Blog.objects.filter(is_active=True)[:3],
        "gallery": Gallery.objects.filter(is_active=True)[:8],
    }
    return render(request, "website/home.html", context)


def about(request):
    return render(request, 'website/about.html')


def services(request):

    context = {

        'services': Service.objects.filter(is_active=True)

    }

    return render(request, 'website/services.html', context)


def portfolio(request):

    context = {

        'projects': Portfolio.objects.filter(is_active=True)

    }

    return render(request, 'website/portfolio.html', context)


def gallery(request):

    context = {

        'gallery': Gallery.objects.filter(is_active=True)

    }

    return render(request, 'website/gallery.html', context)


def blog(request):

    context = {

        'blogs': Blog.objects.filter(is_active=True)

    }

    return render(request, 'website/blog.html', context)


from django.http import JsonResponse
from django.shortcuts import render
from .forms import ContactForm


def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)

        if form.is_valid():
            form.save()
            return JsonResponse({
                "status": "success",
                "message": "Thank you for contacting us. We will get back to you shortly."
            })

        return JsonResponse({"status": "error", "errors": form.errors}, status=400)

    form = ContactForm()
    return render(request, "website/contact.html", {
        "form": form
    })

from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect


def login_view(request):
    if request.user.is_authenticated:
        return redirect("user")

    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, f"Welcome back, {user.first_name or user.username}.")
            return redirect_user(user)
           
        messages.error(request, "Invalid username or password.")

    return render(request, "login.html")

def logout_view(request):
    logout(request)
    messages.success(request, "You have been logged out successfully.")
    return redirect("home")

@transaction.atomic
def apply(request):

    if request.method == "POST":

        form = ApplicationForm(
            request.POST,
            request.FILES
        )

        if form.is_valid():

            email = form.cleaned_data["email"]

            if User.objects.filter(email=email).exists():

                form.add_error(
                    "email",
                    "An account already exists with this email address."
                )

            else:

                # Save the application
                application = form.save(commit=False)
                application.save()

                # Temporary password
                temp_password = application.surname.upper()

                # Create the user
                user = User.objects.create_user(
                    username=email,
                    email=email,
                    password=temp_password,
                    first_name=application.first_name,
                    last_name=application.surname,
                )

                # Populate extra fields if available
                if hasattr(user, "phone"):
                    user.phone = application.phone

                if hasattr(user, "address"):
                    user.address = application.address

                user.save()

                # Link application to user
                application.user = user
                application.save(update_fields=["user"])

                # Log the user in
                authenticated_user = authenticate(
                    request,
                    username=email,
                    password=temp_password,
                )

                if authenticated_user is not None:

                    login(request, authenticated_user)

                messages.success(
                    request,
                    f"Welcome {application.first_name}! "
                    "Your account has been created successfully."
                )

                return redirect("portal")

    else:

        form = ApplicationForm()

    return render(
        request,
        "website/apply.html",
        {
            "form": form
        }
    )


@login_required
def portal(request):
    if request.user.is_staff:
        return redirect("administrator_dashboard")

    return render(
        request,
        "portal/index.html",
        {
            "application": getattr(request.user, "application", None)
        }
    )



@login_required
def admin_dashboard(request):
    total_revenue = (
        Payment.objects.filter(
            p_state=Payment.STATUS_SUCCESSFUL
        ).aggregate(total=Sum("amount"))["total"]
        or Decimal("0.00")
    )
    context = {
        "total_applicants": User.objects.filter(is_staff=False).count(),
        "total_users": User.objects.count(),
        "successful_payments": Payment.objects.filter(
            p_state=Payment.STATUS_SUCCESSFUL
        ).count(),
        "pending_payments": Payment.objects.filter(
            p_state=Payment.STATUS_PENDING
        ).count(),
        "total_revenue": total_revenue,
    }

    return render(request, "admin/index.html", context)




def redirect_user(user):
    if user.is_staff:
        return redirect("administrator_dashboard")
    return redirect("portal")

@login_required
def edit_profile(request):
    application = request.user.application
    if request.method == "POST":
        form = ApplicantProfileForm(request.POST, request.FILES, instance=application,)

        if form.is_valid():
            form.save()
            return JsonResponse({"success": True})

        html = render_to_string("portal/profile/edit_form.html", {"form": form}, request=request,)
        return JsonResponse({"success": False, "html": html})

    form = ApplicantProfileForm(instance=application)
    html = render_to_string("portal/profile/edit_form.html",
        {"form": form}, request=request,)

    return JsonResponse({"html": html})

@login_required
def payments(request):
    items = PaymentItem.objects.filter(active=True)
    payments = Payment.objects.filter(user=request.user)[:10]

    return render(request, "portal/payments/index.html",
        {
            "items": items,
            "payments": payments,
        }
    )

@login_required
def payment_confirm(request, pk):
    item = get_object_or_404(PaymentItem, pk=pk, active=True)

    if request.method == "POST":
        payment = Payment.objects.create(
            user=request.user,
            p_item=item.title,
            p_description=item.description,
            amount=item.amount,
            college_amount=item.amount
        )

        payment = RemitaInvoice.generate(payment)
        if not payment.rrr:
            messages.error(request, payment.ccomment or "Unable to generate RRR.")
            return redirect("payments")

        return redirect("payment_pay", payment.txn_ref)    


    return render(request, "portal/payments/confirm.html",
        {"item": item}
    )


@login_required
def remita_initialize(request, txn_ref):
    payment = get_object_or_404(Payment, txn_ref=txn_ref, user=request.user)
    return render(request, "portal/payments/remita_redirect.html",
        {
            "payment": payment,
        },
    )


@login_required
def payment_pay(request, txn_ref):
    payment = get_object_or_404(Payment,txn_ref=txn_ref, user=request.user)

    if not payment.rrr:
        return redirect("payments")

    return render(request, "portal/payments/pay.html",
        {
            "payment": payment,
            "public_key": settings.REMITA_PUBLIC_KEY,
        }
    )


@login_required
def payment_verify(request):
    if request.method != "POST":
        return JsonResponse({
            "success": False,
            "message": "Invalid request."
        })

    data = json.loads(request.body)
    txn_ref = data.get("txn_ref")
    payment = get_object_or_404(Payment, txn_ref=txn_ref, user=request.user)

    payment = RemitaVerify.verify(payment)
    if payment.p_state == Payment.STATUS_SUCCESSFUL:

        # return JsonResponse({
        #     "success": True,
        #     "redirect_url": reverse(
        #         "payment_receipt",
        #         args=[payment.txn_ref]
        #     )
        # })
        return JsonResponse({
            "success": True,
            "redirect_url": reverse("payments")
        })

    return JsonResponse({
        "success": False,
        "message": payment.r_desc
    })


@login_required
def payment_success(request, txn_ref):
    payment = get_object_or_404(Payment, txn_ref=txn_ref, user=request.user)
    if payment.p_state != "successful":
        return redirect("payments")
    return render(request, "portal/payments/success.html",
        {
            "payment": payment
        }
    )


from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect

from .models import Payment
from .services.remita_verify import RemitaVerify


@login_required
def payment_requery(request, txn_ref):
    payment = get_object_or_404(Payment, txn_ref=txn_ref, user=request.user)
    old_status = payment.p_state
    payment = RemitaVerify.verify(payment)

    if payment.p_state == Payment.STATUS_SUCCESSFUL:
        if old_status != Payment.STATUS_SUCCESSFUL:
            messages.success(request, "Congratulations! Your payment has now been verified successfully.")
        else:
            messages.info(request, "This payment has already been verified.")

    elif payment.p_state == Payment.STATUS_PENDING:
        messages.warning(request, "Payment is still pending. Please try again later.")
    else:
        messages.error(request, payment.r_desc or "Payment could not be verified.")

    return redirect("payments")


@login_required
def payment_receipt(request, txn_ref):
    payment = get_object_or_404(Payment, txn_ref=txn_ref, user=request.user)
    return render(request, "portal/payments/receipt.html",
        {
            "payment": payment,
        }
    )


