# ✅ Register models to show in Django admin
from django.contrib import admin
from django.conf import settings


from django.contrib import admin
from .models import (
    CommissionConfig,
    CommissionSplitConfig,
    CommissionLog,
    GeoRoleAssignment,
    GeoCommissionWallet,
    CommissionPayoutHistory,
    ViralPeWallet,
    ExternalWalletTopUp,
    PaymentTransaction,
)

from django.contrib import admin
from .models import ExternalWalletUsage, ViralPeWalletUsage

@admin.register(ExternalWalletUsage)
class ExternalWalletUsageAdmin(admin.ModelAdmin):
    list_display = ('user', 'amount_used', 'used_for', 'used_on')
    search_fields = ('user__mobile_number', 'used_for')
    list_filter = ('used_on',)
    ordering = ('-used_on',)

@admin.register(ViralPeWalletUsage)
class ViralPeWalletUsageAdmin(admin.ModelAdmin):
    list_display = ('user', 'transaction_type', 'amount_used', 'purpose', 'order_id', 'reference_user', 'used_on')
    list_filter = ('transaction_type', 'used_on')
    search_fields = ('user__mobile_number', 'purpose', 'order_id', 'reference_user__mobile_number')
    ordering = ('-used_on',)

from django.contrib import admin
from .models import ExternalWallet, ExternalWalletTransaction

@admin.register(ExternalWallet)
class ExternalWalletAdmin(admin.ModelAdmin):
    list_display = ('user', 'balance', 'last_updated')
    search_fields = ('user__mobile_number', 'user__email')
    readonly_fields = ('balance', 'last_updated')

@admin.register(ExternalWalletTransaction)
class ExternalWalletTransactionAdmin(admin.ModelAdmin):
    list_display = ('user', 'transaction_type', 'amount', 'purpose', 'reference_user', 'created_at')
    list_filter = ('transaction_type', 'created_at')
    search_fields = ('user__mobile_number', 'purpose', 'order_id')
    readonly_fields = ('user', 'transaction_type', 'amount', 'purpose', 'reference_user', 'order_id', 'created_at')

from django.contrib import admin
from payments.models import CommissionConfig
from recharge.models import Operator

# @admin.register(CommissionConfig)
# class CommissionConfigAdmin(admin.ModelAdmin):
#     list_display = ('operator', 'provider_name', 'provider_percentage', 'fixed_percentage', 'created_at')
#     list_filter = ('operator__service_type', 'provider_name', 'created_at')
#     search_fields = ('provider_name', 'operator__name', 'operator__code')
#     ordering = ('-created_at',)

#     def service_type(self, obj):
#         return obj.operator.service_type
#     service_type.short_description = 'Service Type'


# commissions/admin.py
from django.contrib import admin
from django.conf import settings
from .models import CommissionConfig
from recharge.models import Operator

# commissions/admin.py
from django.contrib import admin
from django.conf import settings
from django.core.exceptions import ValidationError
from .models import CommissionConfig
from .forms import CommissionConfigAdminForm
from recharge.models import Operator

# commissions/admin.py
from django.contrib import admin
from django.conf import settings
from django.core.exceptions import ValidationError
from .models import CommissionConfig
from .forms import CommissionConfigAdminForm

# @admin.register(CommissionConfig)
# class CommissionConfigAdmin(admin.ModelAdmin):
#     form = CommissionConfigAdminForm
#     list_display = ("operator", "provider_name", "provider_percentage", "fixed_percentage", "updated_at")
#     list_filter  = ("provider_name", "operator__service_type", "operator__source")
#     search_fields = ("operator__name",)
#     autocomplete_fields = ("operator",)

#     def save_model(self, request, obj, form, change):
#         # Only check if operator is chosen
#         if getattr(obj, "operator_id", None):
#             src = settings.PROVIDER_SOURCE_MAP.get(obj.provider_name, obj.provider_name)
#             if (obj.operator.source or "").lower() != str(src).lower():
#                 raise ValidationError(
#                     {"operator": f"Operator source '{obj.operator.source}' doesn't match provider '{src}'."}
#                 )
#         super().save_model(request, obj, form, change)

from django.contrib import admin
from .models import CommissionConfig
from .forms import CommissionConfigAdminForm

@admin.register(CommissionConfig)
class CommissionConfigAdmin(admin.ModelAdmin):
    form = CommissionConfigAdminForm

    # Optional: show old values as read-only *display* methods
    def legacy_provider_percentage(self, obj):
        return obj.provider_percentage
    legacy_provider_percentage.short_description = "Legacy provider %"

    def legacy_fixed_percentage(self, obj):
        return obj.fixed_percentage
    legacy_fixed_percentage.short_description = "Legacy fixed %"

    list_display = (
        "operator",
        "provider_name",
        "commission_type",
        "commission_value",
        "legacy_provider_percentage",
        "legacy_fixed_percentage",
        "created_at",
        "updated_at",
    )
    list_filter = ("commission_type", "provider_name", "operator__source")
    search_fields = ("operator__name", "provider_name")
    readonly_fields = ("created_at", "updated_at")  # display-only meta fields

    # If you want to surface legacy values on the edit page as read-only,
    # include the display methods in 'fields' plus 'readonly_fields':
    # fields = (
    #     "operator", "provider_name",
    #     "commission_type", "commission_value",
    #     "legacy_provider_percentage", "legacy_fixed_percentage",
    #     "created_at", "updated_at",
    # )
    # readonly_fields = (
    #     "legacy_provider_percentage", "legacy_fixed_percentage",
    #     "created_at", "updated_at",
    # )



@admin.register(CommissionSplitConfig)
class CommissionSplitConfigAdmin(admin.ModelAdmin):
    list_display = ("role", "percentage", "created_at")
    list_filter = ["role"]  # ✅ Correct – list
    ordering = ("-created_at",)

@admin.register(CommissionLog)
class CommissionLogAdmin(admin.ModelAdmin):
    list_display = ("transaction_id", "user", "role", "amount", "region_type", "is_credited", "timestamp")
    list_filter = ("role", "region_type", "is_credited")
    search_fields = ("transaction_id", "user__mobile_number")
    ordering = ("-timestamp",)

@admin.register(GeoRoleAssignment)
class GeoRoleAssignmentAdmin(admin.ModelAdmin):
    list_display = ("user", "role", "pincode", "district", "state", "vertical", "valid_from", "valid_to")
    list_filter = ("role", "state", "district", "vertical")
    search_fields = ("user__mobile_number", "pincode", "district", "state", "vertical")
    ordering = ("-valid_from",)

@admin.register(GeoCommissionWallet)
class GeoCommissionWalletAdmin(admin.ModelAdmin):
    list_display = ("region_type", "region_value", "balance", "last_updated")
    list_filter = ("region_type",)
    search_fields = ("region_value",)
    ordering = ("-last_updated",)

@admin.register(CommissionPayoutHistory)
class CommissionPayoutHistoryAdmin(admin.ModelAdmin):
    list_display = ("user", "region_type", "region_value", "amount", "paid_on", "paid_by")
    list_filter = ("region_type",)
    search_fields = ("user__mobile_number", "region_value")
    ordering = ("-paid_on",)


@admin.register(ViralPeWallet)
class ViralPeWalletAdmin(admin.ModelAdmin):
    list_display = ("user", "balance", "last_updated")
    search_fields = ("user__mobile_number",)
    ordering = ("-last_updated",)

@admin.register(ExternalWalletTopUp)
class ExternalWalletTopUpAdmin(admin.ModelAdmin):
    list_display = ("user", "amount", "added_by", "added_on")
    list_filter = ("added_by",)
    search_fields = ("user__mobile_number", "added_by__mobile_number")
    ordering = ("-added_on",)

@admin.register(PaymentTransaction)
class PaymentTransactionAdmin(admin.ModelAdmin):
    # list_display = ('user', 'amount', 'status', 'created_at')
    list_display = ('user', 'service', 'amount', 'order_id', 'status', 'created_at')
    search_fields = ('user__first_name', 'user__mobile_number', 'order_id', 'status')
    list_filter = ('status', 'created_at')

from django.contrib import admin
from django.utils.html import format_html
from .models import RechargePaymentSummary
from django.utils import timezone
from recharge.utils import A1TopupAPI
from notifications.services import send_notification
from django.utils.timezone import now
from django.db import transaction
from payments.views import process_recharge_refund

@admin.register(RechargePaymentSummary)
class RechargePaymentSummaryAdmin(admin.ModelAdmin):
    list_display = ['order_id', 'user', 'recharge_amount', 'status_badge','is_refunded', 'updated_at']
    list_filter = ['recharge_status']

    def status_badge(self, obj):
        color = {
            "Success": "green",
            "success": "green",
            "Failure": "red",
            "Pending": "orange",
            "initiated": "gray",
            "error": "pink"
        }.get(obj.recharge_status, "black")

        return format_html(
            '<span style="color:{}; font-weight:bold;">{}</span>',
            color, obj.recharge_status
        )
    status_badge.short_description = "Recharge Status"

# admin.site.unregister(RechargePaymentSummary)
# @admin.register(RechargePaymentSummary)
# class RechargePaymentSummaryAdmin(admin.ModelAdmin):
#     list_display = ['user', 'order_id', 'recharge_amount', 'recharge_status', 'is_refunded', 'refunded_on','status_message','updated_at']
#     list_filter = ['recharge_status', 'is_refunded']
#     actions = ['recheck_pending_recharges', 'process_refunds']
#     readonly_fields = ['recharge_status', 'is_refunded', 'refunded_on']

#     def recheck_pending_recharges(self, request, queryset):
#         a1_api = A1TopupAPI(settings.A1TOPUP_USERNAME, settings.A1TOPUP_PASSWORD)
#         count_success = 0
#         count_failed = 0
#         count_skipped = 0

#         for summary in queryset.filter(recharge_status="Pending"):
#             result = a1_api.check_status(orderid=summary.order_id)
#             raw_status = result.get("status", "").lower()
#             status_map = {
#                 "success": "Success",
#                 "failure": "Failure",
#                 "failed": "Failure",
#                 "pending": "Pending"
#             }
#             new_status = status_map.get(raw_status, "Pending")

#             if new_status != summary.recharge_status:
#                 summary.recharge_status = new_status
#                 summary.gateway_reference = result.get("payment_id") or summary.gateway_reference
#                 summary.full_response = result
#                 summary.updated_at = timezone.now()
#                 summary.save()

#                 context = {
#                     "number": result.get("number") or summary.gateway_reference,
#                     "amount": summary.recharge_amount,
#                     "order_id": summary.order_id
#                 }

#                 if new_status == "Success":
#                     count_success += 1
#                     send_notification(summary.user, "recharge_success", context,
#                         f"Recharge of ₹{summary.recharge_amount} was successful.")
#                 elif new_status == "Failure":
#                     count_failed += 1
#                     send_notification(summary.user, "recharge_failed", context,
#                         f"Recharge of ₹{summary.recharge_amount} failed.")
#             else:
#                 count_skipped += 1

#         self.message_user(
#             request,
#             f"✔ {count_success} marked Success, ❌ {count_failed} marked Failure, ⏳ {count_skipped} still Pending."
#         )

#     recheck_pending_recharges.short_description = "Recheck Pending Recharges"

#     def process_refunds(self, request, queryset):
#         count_refunded = 0
#         count_skipped = 0
#         count_failed = 0

#         for summary in queryset.filter(recharge_status="Failure", is_refunded=False):
#             try:
#                 prev_refunded = summary.is_refunded
#                 process_recharge_refund(summary)
#                 if not prev_refunded and summary.is_refunded:
#                     # ✅ Send notification
#                     send_notification(
#                         summary.user,
#                         type_key="recharge_refund",
#                         context={
#                             'amount': summary.recharge_amount,
#                             'order_id': summary.order_id
#                         },
#                         message=f"Recharge of ₹{summary.recharge_amount} failed and has been refunded."
#                     )
#                     count_refunded += 1
#                 else:
#                     count_skipped += 1
#             except Exception as e:
#                 print("⚠️ Refund failed:", e)
#                 count_failed += 1

#         self.message_user(
#             request,
#             f"💰 {count_refunded} refunded, ❌ {count_failed} failed, ⏭ {count_skipped} skipped."
#         )

#     process_refunds.short_description = "Process Refunds for Failed Recharges"
