"""
Billing Business Logic Admin

NOTE: Most billing models are registered in modules/billing/admin.py 
with full workflow functionality. This file contains legacy/minimal registrations.
"""
from django.contrib import admin
from django.contrib import messages
from django.utils.html import format_html
from unfold.admin import ModelAdmin
from igny8_core.admin.base import AccountAdminMixin, Igny8ModelAdmin
from .models import (
    CreditCostConfig,
    AccountPaymentMethod,
    Invoice,
    Payment,
    CreditPackage,
    PaymentMethodConfig,
)


# CreditCostConfig - DUPLICATE - Registered in modules/billing/admin.py with better features
# Commenting out to avoid conflicts
# @admin.register(CreditCostConfig)
# class CreditCostConfigAdmin(admin.ModelAdmin):
#     ...existing implementation...


# Invoice - DUPLICATE - Registered in modules/billing/admin.py
# Commenting out to avoid conflicts
# @admin.register(Invoice)
# class InvoiceAdmin(AccountAdminMixin, admin.ModelAdmin):
#     ...existing implementation...


# Payment - DUPLICATE - Registered in modules/billing/admin.py with full approval workflow
# Commenting out to avoid conflicts
# @admin.register(Payment)
# class PaymentAdmin(AccountAdminMixin, admin.ModelAdmin):
#     ...existing implementation...


# CreditPackage - DUPLICATE - Registered in modules/billing/admin.py
# Commenting out to avoid conflicts
# @admin.register(CreditPackage)
# class CreditPackageAdmin(admin.ModelAdmin):
#     ...existing implementation...


# PaymentMethodConfig and AccountPaymentMethod are kept here as they're not duplicated
# or have minimal implementations that don't conflict

from import_export.admin import ExportMixin
from import_export import resources


class AccountPaymentMethodResource(resources.ModelResource):
    """Resource class for exporting Account Payment Methods"""
    class Meta:
        model = AccountPaymentMethod
        fields = ('id', 'display_name', 'type', 'account__name', 'is_default',
                  'is_enabled', 'is_verified', 'country_code', 'created_at')
        export_order = fields


@admin.register(AccountPaymentMethod)
class AccountPaymentMethodAdmin(ExportMixin, Igny8ModelAdmin):
    resource_class = AccountPaymentMethodResource
    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']
    actions = [
        'bulk_enable',
        'bulk_disable',
        'bulk_set_default',
        'bulk_delete_methods',
    ]
    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',)
        }),
    )    
    def bulk_enable(self, request, queryset):
        updated = queryset.update(is_enabled=True)
        self.message_user(request, f'{updated} payment method(s) enabled.', messages.SUCCESS)
    bulk_enable.short_description = 'Enable selected payment methods'
    
    def bulk_disable(self, request, queryset):
        updated = queryset.update(is_enabled=False)
        self.message_user(request, f'{updated} payment method(s) disabled.', messages.SUCCESS)
    bulk_disable.short_description = 'Disable selected payment methods'
    
    def bulk_set_default(self, request, queryset):
        from django import forms
        
        if 'apply' in request.POST:
            method_id = request.POST.get('payment_method')
            if method_id:
                method = AccountPaymentMethod.objects.get(pk=method_id)
                # Unset all others for this account
                AccountPaymentMethod.objects.filter(account=method.account).update(is_default=False)
                method.is_default = True
                method.save()
                self.message_user(request, f'{method.display_name} set as default for {method.account.name}.', messages.SUCCESS)
                return
        
        class PaymentMethodForm(forms.Form):
            payment_method = forms.ModelChoiceField(
                queryset=queryset,
                label="Select Payment Method to Set as Default"
            )
        
        from django.shortcuts import render
        return render(request, 'admin/bulk_action_form.html', {
            'title': 'Set Default Payment Method',
            'queryset': queryset,
            'form': PaymentMethodForm(),
            'action': 'bulk_set_default',
        })
    bulk_set_default.short_description = 'Set as default'
    
    def bulk_delete_methods(self, request, queryset):
        count = queryset.count()
        queryset.delete()
        self.message_user(request, f'{count} payment method(s) deleted.', messages.SUCCESS)
    bulk_delete_methods.short_description = 'Delete selected payment methods'