from __future__ import annotations

from django.shortcuts import render, redirect
from django.contrib import messages
from django.urls import reverse

from .models import Organization, OrganizationSite
from .forms import OrganizationForm

from admin_frontend.templatetags.public_urls import public_route
from cms.views import breadcrumbs


def _owner_required(request):
    profile = getattr(request.user, "recycle_profile", None)
    return bool(profile and profile.role == "owner" and (getattr(request, "org", None) is None or profile.organization_id == request.org.id))


@public_route(label="Organization Settings", order=10, icon="cog-6-tooth")
@breadcrumbs(label="Organization Settings", name="org_settings")
def org_settings(request):
    if not request.user.is_authenticated or not _owner_required(request):
        messages.error(request, "Only organization owners can access organization settings.")
        return redirect("admin_frontend:dashboard")

    org = getattr(request, "org", None)
    if not org:
        messages.error(request, "Organization context missing.")
        return redirect("admin_frontend:dashboard")

    if request.method == "POST":
        form = OrganizationForm(request.POST, instance=org)
        if form.is_valid():
            form.save()
            messages.success(request, "Organization updated.")
            return redirect("orgs_admin:org_settings")
        messages.error(request, "Please correct the errors below.")
    else:
        form = OrganizationForm(instance=org)

    return render(request, "orgs/org_settings.html", {"form": form})


@public_route(label="Organization Sites", order=12, icon="link")
@breadcrumbs(label="Organization Sites", name="org_sites")
def org_sites(request):
    if not request.user.is_authenticated or not _owner_required(request):
        messages.error(request, "Only organization owners can access organization sites.")
        return redirect("admin_frontend:dashboard")

    org = getattr(request, "org", None)
    mappings = OrganizationSite.objects.select_related("site").filter(organization=org)

    if request.method == "POST":
        # Simple action: ensure current request.site is mapped to this org
        cur_site = getattr(request, "site", None)
        if not cur_site:
            messages.error(request, "Current site not detected.")
            return redirect("orgs_admin:org_sites")
        mapping, created = OrganizationSite.objects.get_or_create(site=cur_site, defaults={"organization": org})
        if not created and mapping.organization_id != org.id:
            messages.error(request, "This site is already mapped to another organization.")
        else:
            messages.success(request, "Current site mapped to this organization.")
        return redirect("orgs_admin:org_sites")

    return render(request, "orgs/org_sites.html", {"mappings": mappings, "current_site": getattr(request, "site", None)})

