"""
Billing Business Logic Admin
"""
from django.contrib import admin
from django.utils.html import format_html
from igny8_core.admin.base import AccountAdminMixin
from .models import (
    CreditCostConfig,
    AccountPaymentMethod,
    Invoice,
    Payment,
    CreditPackage,
    PaymentMethodConfig,
)


@admin.register(CreditCostConfig)
class CreditCostConfigAdmin(admin.ModelAdmin):
    list_display = [
        'operation_type',
        'display_name',
        'credits_cost_display',
        'unit',
        'is_active',
        'cost_change_indicator',
        'updated_at',
        'updated_by'
    ]
    
    list_filter = ['is_active', 'unit', 'updated_at']
    search_fields = ['operation_type', 'display_name', 'description']
    
    fieldsets = (
        ('Operation', {
            'fields': ('operation_type', 'display_name', 'description')
        }),
        ('Cost Configuration', {
            'fields': ('credits_cost', 'unit', 'is_active')
        }),
        ('Audit Trail', {
            'fields': ('previous_cost', 'updated_by', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    readonly_fields = ['created_at', 'updated_at', 'previous_cost']
    
    def credits_cost_display(self, obj):
        """Show cost with color coding"""
        if obj.credits_cost >= 20:
            color = 'red'
        elif obj.credits_cost >= 10:
            color = 'orange'
        else:
            color = 'green'
        return format_html(
            '<span style="color: {}; font-weight: bold;">{} credits</span>',
            color,
            obj.credits_cost
        )
    credits_cost_display.short_description = 'Cost'
    
    def cost_change_indicator(self, obj):
        """Show if cost changed recently"""
        if obj.previous_cost is not None:
            if obj.credits_cost > obj.previous_cost:
                icon = '📈'  # Increased
                color = 'red'
            elif obj.credits_cost < obj.previous_cost:
                icon = '📉'  # Decreased
                color = 'green'
            else:
                icon = '➡️'  # Same
                color = 'gray'
            
            return format_html(
                '{} <span style="color: {};">({} → {})</span>',
                icon,
                color,
                obj.previous_cost,
                obj.credits_cost
            )
        return '—'
    cost_change_indicator.short_description = 'Recent Change'
    
    def save_model(self, request, obj, form, change):
        """Track who made the change"""
        obj.updated_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(Invoice)
class InvoiceAdmin(AccountAdminMixin, admin.ModelAdmin):
    list_display = [
        'invoice_number',
        'account',
        'status',
        'total',
        'currency',
        'invoice_date',
        'due_date',
        'subscription',
    ]
    list_filter = ['status', 'currency', 'invoice_date', 'account']
    search_fields = ['invoice_number', 'account__name', 'subscription__id']
    readonly_fields = ['created_at', 'updated_at']


@admin.register(Payment)
class PaymentAdmin(AccountAdminMixin, admin.ModelAdmin):
    list_display = [
        'id',
        'invoice',
        'account',
        'payment_method',
        'status',
        'amount',
        'currency',
        'processed_at',
    ]
    list_filter = ['status', 'payment_method', 'currency', 'created_at']
    search_fields = ['invoice__invoice_number', 'account__name', 'stripe_payment_intent_id', 'paypal_order_id']
    readonly_fields = ['created_at', 'updated_at']


@admin.register(CreditPackage)
class CreditPackageAdmin(admin.ModelAdmin):
    list_display = ['name', 'slug', 'credits', 'price', 'discount_percentage', 'is_active', 'is_featured', 'sort_order']
    list_filter = ['is_active', 'is_featured']
    search_fields = ['name', 'slug']
    readonly_fields = ['created_at', 'updated_at']


@admin.register(PaymentMethodConfig)
class PaymentMethodConfigAdmin(admin.ModelAdmin):
    list_display = ['country_code', 'payment_method', 'is_enabled', 'display_name', 'sort_order']
    list_filter = ['payment_method', 'is_enabled', 'country_code']
    search_fields = ['country_code', 'display_name', 'payment_method']
    readonly_fields = ['created_at', 'updated_at']


@admin.register(AccountPaymentMethod)
class AccountPaymentMethodAdmin(admin.ModelAdmin):
    list_display = [
        'display_name',
        'type',
        'account',
        'is_default',
        'is_enabled',
        'country_code',
        'is_verified',
        'updated_at',
    ]
    list_filter = ['type', 'is_default', 'is_enabled', 'is_verified', 'country_code']
    search_fields = ['display_name', 'account__name', 'account__id']
    readonly_fields = ['created_at', 'updated_at']
    fieldsets = (
        ('Payment Method', {
            'fields': ('account', 'type', 'display_name', 'is_default', 'is_enabled', 'is_verified', 'country_code')
        }),
        ('Instructions / Metadata', {
            'fields': ('instructions', 'metadata')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
