from django.contrib import admin
from django.utils.html import format_html
from .models import EscrowTransaction, EscrowLog, EscrowDeliveryPhoto, VendorPayoutAccount


class EscrowLogInline(admin.TabularInline):
    model = EscrowLog
    extra = 0
    readonly_fields = ["action", "previous_status", "new_status", "note", "actor", "created_at"]
    can_delete = False


class EscrowDeliveryPhotoInline(admin.TabularInline):
    model = EscrowDeliveryPhoto
    extra = 0
    readonly_fields = ["photo_preview", "caption", "uploaded_at"]

    def photo_preview(self, obj):
        if obj.photo:
            return format_html('<img src="{}" style="height:80px;border-radius:6px;">', obj.photo.url)
        return "—"
    photo_preview.short_description = "Photo"


@admin.register(EscrowTransaction)
class EscrowTransactionAdmin(admin.ModelAdmin):
    list_display = [
        "short_id", "order_number", "vendor", "amount_display",
        "status", "created_at"
    ]
    list_filter = ["status", "currency", "created_at"]
    search_fields = ["order__order_number", "vendor__store_name", "paystack_reference"]
    readonly_fields = [
        "id", "paystack_reference", "paystack_access_code",
        "paystack_authorization_url", "paystack_charge_id",
        "paystack_transfer_code", "buyer_confirmation_token",
        "created_at", "updated_at",
    ]
    inlines = [EscrowLogInline, EscrowDeliveryPhotoInline]

    def short_id(self, obj):
        return str(obj.id)[:8]
    short_id.short_description = "ID"

    def order_number(self, obj):
        return obj.order.order_number if obj.order else "—"
    order_number.short_description = "Order"

    def amount_display(self, obj):
        return f"GHS {obj.amount}"
    amount_display.short_description = "Amount"


@admin.register(VendorPayoutAccount)
class VendorPayoutAccountAdmin(admin.ModelAdmin):
    list_display = ["vendor", "account_type", "account_name", "account_number", "paystack_recipient_code"]
    search_fields = ["vendor__store_name", "account_name", "account_number"]
    readonly_fields = ["paystack_recipient_code", "created_at", "updated_at"]