from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
import json

from .models import (
    MpesaConfiguration, MpesaCallback, 
    MpesaAccessToken, PaymentAllocation
)
from loans.models import MpesaTransaction


@admin.register(MpesaConfiguration)
class MpesaConfigurationAdmin(admin.ModelAdmin):
    list_display = ['business_short_code', 'environment', 'is_active', 'created_at']
    list_filter = ['environment', 'is_active']
    search_fields = ['business_short_code', 'consumer_key']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('Basic Configuration', {
            'fields': ('environment', 'business_short_code', 'is_active')
        }),
        ('API Credentials', {
            'fields': ('consumer_key', 'consumer_secret', 'passkey'),
            'classes': ('collapse',)
        }),
        ('Callback URLs', {
            'fields': ('validation_url', 'confirmation_url', 'response_type')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )


# MpesaTransaction admin is handled in loans app


@admin.register(MpesaCallback)
class MpesaCallbackAdmin(admin.ModelAdmin):
    list_display = ['callback_type', 'transaction_link', 'processed', 'created_at']
    list_filter = ['callback_type', 'processed', 'created_at']
    search_fields = ['raw_data']
    readonly_fields = ['raw_data_display', 'response_sent_display', 'created_at']
    
    fieldsets = (
        ('Callback Information', {
            'fields': ('callback_type', 'transaction', 'processed', 'ip_address', 'user_agent')
        }),
        ('Data', {
            'fields': ('raw_data_display', 'response_sent_display'),
            'classes': ('collapse',)
        }),
        ('Timestamps', {
            'fields': ('created_at',)
        })
    )
    
    def transaction_link(self, obj):
        if obj.transaction:
            url = reverse('admin:loans_mpesatransaction_change', args=[obj.transaction.pk])
            trans_id = obj.transaction.trans_id or obj.transaction.mpesa_transaction_id or 'N/A'
            return format_html('<a href="{}">{}</a>', url, trans_id)
        return 'No transaction'
    transaction_link.short_description = 'Transaction'
    
    def raw_data_display(self, obj):
        return format_html('<pre>{}</pre>', json.dumps(obj.raw_data, indent=2))
    raw_data_display.short_description = 'Raw Data'
    
    def response_sent_display(self, obj):
        if obj.response_sent:
            return format_html('<pre>{}</pre>', json.dumps(obj.response_sent, indent=2))
        return 'No response'
    response_sent_display.short_description = 'Response Sent'


@admin.register(MpesaAccessToken)
class MpesaAccessTokenAdmin(admin.ModelAdmin):
    list_display = ['configuration', 'expires_at', 'is_expired_display', 'created_at']
    list_filter = ['expires_at', 'created_at']
    readonly_fields = ['access_token', 'expires_at', 'created_at']
    
    def is_expired_display(self, obj):
        if obj.is_expired():
            return format_html('<span style="color: red;">Expired</span>')
        return format_html('<span style="color: green;">Valid</span>')
    is_expired_display.short_description = 'Status'


@admin.register(PaymentAllocation)
class PaymentAllocationAdmin(admin.ModelAdmin):
    list_display = ['mpesa_transaction', 'loan', 'allocated_amount', 'created_at']
    list_filter = ['created_at']
    search_fields = ['mpesa_transaction__trans_id', 'loan__loan_number']
    readonly_fields = ['created_at']


# ---------------------------------------------------------------------------
# Developer Payment Admin (PhinTech Solutions Company Ltd)
# ---------------------------------------------------------------------------
from .developer_payment_models import DeveloperPayment


@admin.register(DeveloperPayment)
class DeveloperPaymentAdmin(admin.ModelAdmin):
    list_display = [
        'reference', 'amount', 'payment_type_display', 'payer_phone',
        'status_display', 'mpesa_receipt', 'initiated_by', 'created_at',
    ]
    list_filter = ['status', 'payment_type', 'created_at']
    search_fields = ['reference', 'description', 'mpesa_receipt', 'payer_phone',
                     'initiated_by__first_name', 'initiated_by__last_name']
    ordering = ['-created_at']
    readonly_fields = [
        'reference', 'lipia_checkout_id', 'lipia_transaction_id',
        'mpesa_receipt', 'raw_initiation_response', 'raw_callback_data',
        'created_at', 'updated_at', 'completed_at',
    ]

    fieldsets = (
        ('Payment Details', {
            'fields': ('reference', 'amount', 'payment_type', 'description', 'payer_phone', 'initiated_by')
        }),
        ('Status', {
            'fields': ('status', 'failure_reason', 'admin_notes')
        }),
        ('LipiaOnline / M-Pesa', {
            'fields': ('lipia_checkout_id', 'lipia_transaction_id', 'mpesa_receipt'),
        }),
        ('Raw API Data', {
            'fields': ('raw_initiation_response', 'raw_callback_data'),
            'classes': ('collapse',),
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at', 'completed_at'),
            'classes': ('collapse',),
        }),
    )

    def status_display(self, obj):
        colours = {
            'completed': 'green', 'processing': '#0d6efd',
            'pending': '#f59e0b', 'failed': 'red', 'cancelled': 'grey',
        }
        colour = colours.get(obj.status, 'grey')
        return format_html(
            '<span style="color:{};font-weight:bold;">{}</span>',
            colour, obj.get_status_display()
        )
    status_display.short_description = 'Status'

    def payment_type_display(self, obj):
        return obj.get_payment_type_display()
    payment_type_display.short_description = 'Type'
