from __future__ import annotations

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.urls import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from orgs.models import Organization
from recycle_core.models import ProvidedService
from recycle_core.models import Material, ScrapListing, PickupOrder
from cms.models import Post, PostCategory

from .forms import PickupRequestForm, ContactForm
from .models import Lead
from recycle_core.controllers.pickup_request import (
    PickupRequestController,
    PickupRequestData,
)


def home(request):
    org = getattr(request, "org", None)
    posts_qs = Post.objects.all()
    if org is not None:
        posts_qs = posts_qs.filter(organization=org)
    posts = posts_qs.order_by("-published_at")[:3]

    listings_qs = ScrapListing.objects.filter(is_public=True)
    if org is not None:
        listings_qs = listings_qs.filter(organization=org)
    listings = listings_qs.order_by("-created_at")[:6]

    materials_qs = Material.objects.all().order_by("name")
    if org is not None:
        materials_qs = materials_qs.filter(organization=org)
    materials = materials_qs[:12]

    services_qs = ProvidedService.objects.none()
    if org is not None:
        services_qs = ProvidedService.objects.filter(organization=org, is_enabled=True).order_by("display_order", "id")
    services = list(services_qs)

    pickup_form = PickupRequestForm()
    contact_form = ContactForm()

    return render(
        request,
        "public_frontend/home.html",
        {
            "posts": posts,
            "listings": listings,
            "materials": materials,
            "services": services,
            "pickup_form": pickup_form,
            "contact_form": contact_form,
            "org": org,
        },
    )


def materials_list(request):
    org = getattr(request, "org", None)
    qs = Material.objects.all().order_by("name")
    if org is not None:
        qs = qs.filter(organization=org)
    return render(request, "public_frontend/materials_list.html", {"materials": qs, "org": org})


def listings_list(request):
    org = getattr(request, "org", None)
    qs = ScrapListing.objects.filter(is_public=True, status=ScrapListing.STATUS_OPEN).order_by("-created_at")
    if org is not None:
        qs = qs.filter(organization=org)
    paginator = Paginator(qs, 12)
    page = request.GET.get("page")
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    return render(request, "public_frontend/listings_list.html", {"page_obj": page_obj, "listings": page_obj.object_list, "org": org})


def listing_detail(request, pk: int):
    org = getattr(request, "org", None)
    base_qs = ScrapListing.objects.filter(is_public=True)
    if org is not None:
        base_qs = base_qs.filter(organization=org)
    listing = get_object_or_404(base_qs, pk=pk)
    return render(request, "public_frontend/listing_detail.html", {"listing": listing, "org": org})


def service_detail(request, pk: int):
    org = getattr(request, "org", None)
    base_qs = ProvidedService.objects.filter(is_enabled=True)
    if org is not None:
        base_qs = base_qs.filter(organization=org)
    service = get_object_or_404(base_qs, pk=pk)
    return render(request, "public_frontend/service_detail.html", {"service": service, "org": org})


def pickup_request(request):
    org = getattr(request, "org", None)
    form = PickupRequestForm(request.POST or None, request.FILES or None)
    if request.method == "POST":
        if not org:
            messages.error(request, "Organization context missing.")
            return redirect("public_frontend:pickup_request")
        if form.is_valid():
            ctrl = PickupRequestController()
            data = PickupRequestData(
                organization=org,
                name=form.cleaned_data.get("name"),
                email=form.cleaned_data.get("email", ""),
                phone=form.cleaned_data.get("phone", ""),
                address=form.cleaned_data.get("address", ""),
                materials=form.cleaned_data.get("materials", ""),
                preferred_at=form.cleaned_data.get("preferred_at"),
                files=request.FILES.getlist("photos") if hasattr(request, "FILES") and "photos" in request.FILES else [],
            )
            result = ctrl.submit(data)
            if result.ok:
                messages.success(request, "Thanks! Your pickup request was submitted.")
                return redirect("public_frontend:home")
            else:
                messages.error(request, result.error or "Unable to submit your request.")
        else:
            messages.error(request, "Please correct the errors below.")
    return render(request, "public_frontend/pickup_request.html", {"form": form, "org": org})


def contact(request):
    org = getattr(request, "org", None)
    form = ContactForm(request.POST or None)
    if request.method == "POST":
        if not org:
            messages.error(request, "Organization context missing.")
            return redirect("public_frontend:contact")
        if form.is_valid():
            Lead.objects.create(
                organization=org,
                name=form.cleaned_data["name"],
                email=form.cleaned_data["email"],
                phone=form.cleaned_data.get("phone", ""),
                subject=form.cleaned_data.get("subject", ""),
                message=form.cleaned_data.get("message", ""),
                source="contact",
            )
            messages.success(request, "Thanks! We will get back to you shortly.")
            return redirect("public_frontend:home")
        messages.error(request, "Please correct the errors below.")
    return render(request, "public_frontend/contact.html", {"form": form, "org": org})


def blog_list(request):
    org = getattr(request, "org", None)
    qs = Post.objects.all().order_by("-published_at", "-created_at")
    if org is not None:
        qs = qs.filter(organization=org)
    paginator = Paginator(qs, 10)
    page = request.GET.get("page")
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    return render(request, "public_frontend/blog_list.html", {"page_obj": page_obj, "posts": page_obj.object_list, "org": org})


def blog_detail(request, slug: str):
    org = getattr(request, "org", None)
    base_qs = Post.objects.all()
    if org is not None:
        base_qs = base_qs.filter(organization=org)
    post = get_object_or_404(base_qs, slug=slug)
    # Ensure markdown is rendered; fallback to raw content if needed
    html = getattr(post, "content_html", None) or getattr(post, "content", "")
    return render(request, "public_frontend/blog_detail.html", {"post": post, "html": html, "org": org})
