from django.conf import settings
from django.core.mail import send_mail
from django.db.models import Count, Q
from django.shortcuts import get_object_or_404, redirect, render

from .forms import ContactInquiryForm
from .models import Category, ContactInquiry, Product


SERVICE_HIGHLIGHTS = [
    {
        "title": "Trauringe & Beratung",
        "text": "Individuelle Beratung für Trauringe, Materialien und Gravuren – persönlich im Geschäft oder per Anfrage.",
    },
    {
        "title": "Goldschmiedeservice",
        "text": "Ringweitenänderung, Reinigung, Umarbeitung und Reparaturen mit viel Erfahrung und Fingerspitzengefühl.",
    },
    {
        "title": "Uhren & Revision",
        "text": "Ausgewählte Uhren und fachkundige Unterstützung bei Pflege, Wartung und Reparatur wertvoller Zeitmesser.",
    },
    {
        "title": "Perlen, Ohrschmuck & Extras",
        "text": "Perlkettenservice, Ohrlochstechen mit STUDEX-System sowie Geschenkgutscheine für besondere Anlässe.",
    },
]


PROCESS_STEPS = [
    {
        "step": "01",
        "title": "Kollektion entdecken",
        "text": "Filtern Sie die Kollektion nach Kategorie und lassen Sie sich inspirieren.",
    },
    {
        "step": "02",
        "title": "Per Telefon oder E-Mail anfragen",
        "text": "Zu jedem Produkt gelangen Sie in wenigen Klicks zur passenden Kontaktmöglichkeit.",
    },
    {
        "step": "03",
        "title": "Persönliche Beratung im Store",
        "text": "Im Geschäft in Leverkusen klärt das Team Details, Anpassungen und Verfügbarkeit.",
    },
]


def _catalog_categories():
    return Category.objects.annotate(
        product_total=Count("products", filter=Q(products__is_active=True))
    )


def _send_inquiry_notification(inquiry):
    if not settings.CONTACT_EMAIL_TO:
        return

    subject = inquiry.subject or "Neue Anfrage über die Website"
    lines = [
        f"Name: {inquiry.name}",
        f"E-Mail: {inquiry.email}",
        f"Telefon: {inquiry.phone or '-'}",
        f"Bevorzugte Kontaktart: {inquiry.get_preferred_contact_method_display()}",
        f"Produkt: {inquiry.product.name if inquiry.product else 'Allgemeine Beratung'}",
        "",
        inquiry.message,
    ]

    try:
        send_mail(
            subject=f"Website-Anfrage: {subject}",
            message="\n".join(lines),
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=settings.CONTACT_EMAIL_TO,
            fail_silently=True,
            reply_to=[inquiry.email],
        )
    except Exception:
        return


def home(request):
    featured_products = Product.objects.filter(is_active=True, is_featured=True).select_related("category")[:4]
    categories = _catalog_categories().filter(product_total__gt=0)

    context = {
        "meta_title": "Juwelier Thelen | Moderner Schmuck- & Trauringkatalog",
        "meta_description": "Moderner Katalog für Trauringe, Schmuck, Uhren und Goldschmiedeservice – mit schneller Kontaktaufnahme per Telefon oder E-Mail.",
        "featured_products": featured_products,
        "categories": categories,
        "service_highlights": SERVICE_HIGHLIGHTS,
        "process_steps": PROCESS_STEPS,
    }
    return render(request, "core/index.html", context)


def catalog(request):
    selected_category = request.GET.get("category", "").strip()
    query = request.GET.get("q", "").strip()

    products = Product.objects.filter(is_active=True).select_related("category")
    if selected_category:
        products = products.filter(category__slug=selected_category)
    if query:
        products = products.filter(
            Q(name__icontains=query)
            | Q(short_description__icontains=query)
            | Q(description__icontains=query)
            | Q(material__icontains=query)
            | Q(category__name__icontains=query)
        )

    context = {
        "meta_title": "Katalog | Juwelier Thelen",
        "meta_description": "Entdecken Sie Trauringe, Schmuck und Uhren – klar gefiltert und bereit für eine persönliche Beratung.",
        "products": products,
        "categories": _catalog_categories(),
        "selected_category": selected_category,
        "query": query,
    }
    return render(request, "core/catalog.html", context)


def product_detail(request, slug):
    product = get_object_or_404(
        Product.objects.filter(is_active=True).select_related("category"),
        slug=slug,
    )
    related_products = (
        Product.objects.filter(is_active=True, category=product.category)
        .exclude(pk=product.pk)
        .select_related("category")[:3]
    )

    context = {
        "meta_title": f"{product.name} | Juwelier Thelen",
        "meta_description": product.short_description,
        "product": product,
        "related_products": related_products,
    }
    return render(request, "core/product_detail.html", context)


def contact(request):
    selected_product = None
    product_slug = request.GET.get("product", "").strip()

    if product_slug:
        selected_product = Product.objects.filter(is_active=True, slug=product_slug).first()

    if request.method == "POST":
        form = ContactInquiryForm(request.POST)
        if form.is_valid():
            inquiry = form.save()
            _send_inquiry_notification(inquiry)
            request.session["contact_inquiry_id"] = inquiry.pk
            return redirect("contact_success")
    else:
        initial = {}
        if selected_product:
            initial["product"] = selected_product
            initial["subject"] = f"Anfrage zu {selected_product.name}"
        form = ContactInquiryForm(initial=initial)

    context = {
        "meta_title": "Kontakt | Juwelier Thelen",
        "meta_description": "Fragen zu Trauringen, Schmuck, Uhren oder Serviceleistungen? Kontaktieren Sie Juwelier Thelen per Telefon oder E-Mail.",
        "form": form,
        "selected_product": selected_product,
    }
    return render(request, "core/contact.html", context)


def contact_success(request):
    inquiry_id = request.session.get("contact_inquiry_id")
    inquiry = None
    if inquiry_id:
        inquiry = ContactInquiry.objects.filter(pk=inquiry_id).select_related("product").first()

    context = {
        "meta_title": "Anfrage erhalten | Juwelier Thelen",
        "meta_description": "Vielen Dank für Ihre Anfrage. Das Team meldet sich zeitnah telefonisch oder per E-Mail zurück.",
        "inquiry": inquiry,
    }
    return render(request, "core/contact_success.html", context)
