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 Material, ScrapListing, PickupOrder
from cms.models import Post, PostCategory

from .forms import PickupRequestForm, ContactForm
from .models import Lead


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]
    return render(request, "public_frontend/home.html", {"posts": posts, "listings": listings, "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 pickup_request(request):
    org = getattr(request, "org", None)
    form = PickupRequestForm(request.POST 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():
            # Store as a Lead for staff to process; PickupOrder requires customer/site
            message = (
                f"Pickup Request\n"
                f"Address: {form.cleaned_data.get('address')}\n"
                f"Preferred: {form.cleaned_data.get('preferred_at') or ''}\n"
                f"Materials: {form.cleaned_data.get('materials') or ''}"
            )
            Lead.objects.create(
                organization=org,
                name=form.cleaned_data.get('name'),
                email=form.cleaned_data.get('email',''),
                phone=form.cleaned_data.get('phone',''),
                subject='Pickup Request',
                message=message,
                source='pickup_request',
            )
            messages.success(request, "Thanks! Your pickup request was submitted.")
            return redirect("public_frontend:home")
        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})
