from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from .models import Hat, Customer, Purchase


@admin.register(Hat)
class HatAdmin(admin.ModelAdmin):
    list_display = ["name", "price", "status", "created_at", "published_at", "sold_at"]
    list_filter = ["status", "created_at"]
    search_fields = ["name", "description"]
    prepopulated_fields = {"slug": ("name",)}
    readonly_fields = ["created_at", "updated_at", "sold_at"]
    fieldsets = (
        (None, {"fields": ("name", "slug", "description", "price", "image")}),
        (
            "Status",
            {
                "fields": (
                    "status",
                    "published_at",
                    "sold_at",
                    "stripe_payment_intent_id",
                )
            },
        ),
        (
            "Metadata",
            {"fields": ("created_at", "updated_at"), "classes": ("collapse",)},
        ),
    )
    actions = ["publish_first_dibs", "publish_available", "mark_sold"]

    def publish_first_dibs(self, request, queryset):
        for hat in queryset.filter(status=Hat.Status.DRAFT):
            hat.status = Hat.Status.FIRST_DIBS
            hat.published_at = timezone.now()
            hat.save()
            self.send_first_dibs_emails(hat, request)
        self.message_user(request, f"{queryset.count()} hats published for First Dibs.")

    def publish_available(self, request, queryset):
        for hat in queryset:
            hat.status = Hat.Status.AVAILABLE
            hat.published_at = timezone.now()
            hat.save()
        self.message_user(request, f"{queryset.count()} hats published as available.")

    def mark_sold(self, request, queryset):
        for hat in queryset:
            hat.status = Hat.Status.SOLD
            hat.sold_at = timezone.now()
            hat.save()
        self.message_user(request, f"{queryset.count()} hats marked as sold.")

    def send_first_dibs_emails(self, hat, request):
        prior_customers = Customer.objects.filter(
            is_active=True, purchases__isnull=False
        ).distinct()

        for customer in prior_customers:
            from django.urls import reverse

            hat_url = request.build_absolute_uri(
                reverse("hat_detail", kwargs={"slug": hat.slug})
            )

            subject = f"First Dibs: New Hat Available - {hat.name}"
            context = {
                "customer": customer,
                "hat": hat,
                "hat_url": hat_url,
            }

            try:
                send_mail(
                    subject=subject,
                    message=f"""
Hi {customer.name},

A new hat has been added to HatYeti.com!

{hat.name}
{hat.description}
Price: ${hat.price}

You have exclusive access for the next 3 days before it goes public.

Get it here: {hat_url}

Happy hatting!
- The Hat Yeti
                    """.strip(),
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[customer.email],
                    html_message=render_to_string(
                        "hats/emails/first_dibs.html", context
                    ),
                    fail_silently=False,
                )
            except Exception as e:
                self.message_user(
                    request, f"Failed to send email to {customer.email}: {e}"
                )

    publish_first_dibs.short_description = "Publish for First Dibs (sends emails)"


@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    list_display = ["email", "name", "has_purchased", "is_active", "created_at"]
    list_filter = ["is_active", "created_at"]
    search_fields = ["email", "name"]
    readonly_fields = ["created_at"]

    @admin.display(boolean=True)
    def has_purchased(self, obj):
        return obj.has_purchased

    has_purchased.short_description = "Has Purchased"


@admin.register(Purchase)
class PurchaseAdmin(admin.ModelAdmin):
    list_display = ["customer", "hat", "amount_paid", "created_at"]
    list_filter = ["created_at"]
    search_fields = ["customer__email", "customer__name", "hat__name"]
    readonly_fields = ["created_at"]
