# subscriptions/admin.py
from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from .models import Subscription, PaymentTransaction, SaasPromoCode


@admin.register(Subscription)
class SubscriptionAdmin(admin.ModelAdmin):
    list_display = (
        'company', 'plan', 'billing_cycle', 'start_date', 'expiry_date',
        'is_trial', 'is_active', 'payment_status', 'days_remaining_display',
    )
    list_filter = ('is_trial', 'is_active', 'payment_status', 'billing_cycle', 'plan')
    search_fields = ('company__name', 'company__slug', 'plan__name')
    readonly_fields = ('created_at', 'updated_at', 'days_remaining')
    raw_id_fields = ('company', 'plan', 'pending_downgrade_plan')

    def days_remaining_display(self, obj):
        dr = obj.days_remaining
        if dr is None:
            return '—'
        if dr == 0:
            return format_html('<span style="color:red">Expired</span>')
        elif dr <= 3:
            return format_html('<span style="color:orange">{} days</span>', dr)
        return f"{dr} days"
    days_remaining_display.short_description = 'Days Left'

    actions = ['activate_selected', 'deactivate_selected']

    def activate_selected(self, request, queryset):
        queryset.update(is_active=True, payment_status='paid')
        self.message_user(request, f"{queryset.count()} subscription(s) activated.")
    activate_selected.short_description = "✅ Activate selected subscriptions"

    def deactivate_selected(self, request, queryset):
        queryset.update(is_active=False)
        self.message_user(request, f"{queryset.count()} subscription(s) deactivated.")
    deactivate_selected.short_description = "❌ Deactivate selected subscriptions"


@admin.register(PaymentTransaction)
class PaymentTransactionAdmin(admin.ModelAdmin):
    list_display = (
        'payment_reference', 'company', 'plan', 'billing_cycle',
        'gateway', 'final_amount', 'status', 'promo_code_used',
        'created_at', 'paid_at', 'mark_paid_link',
    )
    list_filter = ('status', 'gateway', 'billing_cycle', 'plan')
    search_fields = (
        'payment_reference', 'monnify_reference', 'gateway_reference',
        'company__name', 'company__slug', 'promo_code_used',
    )
    readonly_fields = (
        'payment_reference', 'monnify_reference', 'gateway_reference',
        'gateway', 'created_at', 'paid_at',
        'raw_webhook_payload',
    )
    raw_id_fields = ('company', 'plan', 'subscription')

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('company', 'plan')

    def mark_paid_link(self, obj):
        """Inline 'Confirm Payment' button for pending / manual transactions."""
        if obj.status == 'paid':
            return format_html('<span style="color:green;font-weight:600;">✓ Paid</span>')
        url = reverse('subscriptions:confirm_manual_payment', args=[obj.payment_reference])
        return format_html(
            '<a href="{}" '
            'style="background:#059669;color:#fff;padding:3px 10px;border-radius:4px;'
            'text-decoration:none;font-size:12px;font-weight:600;">'
            '✔ Confirm Payment</a>',
            url
        )
    mark_paid_link.short_description = 'Action'

    actions = ['mark_selected_as_paid']

    def mark_selected_as_paid(self, request, queryset):
        """Bulk action: mark selected pending transactions as paid and activate subscriptions."""
        from .services import activate_subscription_for_transaction
        activated = 0
        errors = 0
        for txn in queryset.filter(status='pending'):
            try:
                if not txn.gateway or txn.gateway not in ('monnify', 'paystack', 'free'):
                    txn.gateway = 'manual'
                txn.payment_method = txn.payment_method or 'Manual Bank Transfer'
                txn.save(update_fields=['gateway', 'payment_method'])
                activate_subscription_for_transaction(txn)
                activated += 1
            except Exception:
                errors += 1
        msg = f"{activated} subscription(s) activated."
        if errors:
            msg += f" {errors} error(s) — check server logs."
        self.message_user(request, msg)
    mark_selected_as_paid.short_description = "✅ Mark as Paid & Activate Subscription"


@admin.register(SaasPromoCode)
class SaasPromoCodeAdmin(admin.ModelAdmin):
    list_display = (
        'code', 'discount_type', 'discount_value', 'valid_from', 'valid_until',
        'usage_count', 'max_usage', 'is_active', 'is_valid_display',
    )
    list_filter = ('is_active', 'discount_type')
    search_fields = ('code', 'description')
    filter_horizontal = ('allowed_plans',)
    readonly_fields = ('usage_count', 'created_at')

    def is_valid_display(self, obj):
        if obj.is_valid:
            return format_html('<span style="color:green">✓ Valid</span>')
        return format_html('<span style="color:red">✗ Invalid</span>')
    is_valid_display.short_description = 'Status'
