# hub/services/templatetags/contact_tags.py
from django import template
from hub.services.forms import LeadForm
from hub.services.models import Service, ServiceOffering, Plan
import time

register = template.Library()


@register.inclusion_tag("services/embedded_contact_form.html", takes_context=True)
def embedded_contact_form(
    context,
    source=None,
    details=None,
    service=None,
    offering_id=None,
    plan_id=None,
    choices=None,
    choice_label=None,
):
    """
    Renders an embedded contact form with optional service context information.

    Usage:
    {% load contact_tags %}
    {% embedded_contact_form source="Partner Page" details="ACME Corp" %}
    {% embedded_contact_form service=service offering_id=offering.id plan_id=plan.id %}
    {% embedded_contact_form service=service offering_id=offering.id choices=offering.plans.all choice_label="Select a Plan" %}
    """
    request = context["request"]
    form = LeadForm()

    # Add timestamp for spam protection
    timestamp = int(time.time())

    service_obj = None
    offering_obj = None
    plan_obj = None

    # Process choices if they're QuerySet objects (like plans)
    processed_choices = None
    if choices:
        processed_choices = [(str(choice.id), choice.name) for choice in choices]

    # Resolve service/offering/plan objects if IDs provided
    if service and isinstance(service, str):
        try:
            service_obj = Service.objects.get(slug=service)
        except Service.DoesNotExist:
            pass
    elif service:
        service_obj = service

    if offering_id and service_obj:
        try:
            offering_obj = ServiceOffering.objects.get(
                id=offering_id, service=service_obj
            )
        except ServiceOffering.DoesNotExist:
            pass

    if plan_id and offering_obj:
        try:
            plan_obj = Plan.objects.get(id=plan_id, offering=offering_obj)
        except Plan.DoesNotExist:
            pass

    return {
        "form": form,
        "source": source,
        "details": details,
        "service": service_obj,
        "offering": offering_obj,
        "plan": plan_obj,
        "request": request,
        "choices": processed_choices,
        "choice_label": choice_label,
        "timestamp": timestamp,
    }
