from django.contrib import admin
from django.utils.html import format_html
from .models import (
    Package,
    PackageFeature,
    ForeignerLead,
    ConsultationRequest,
    ContactMessage,
    ConfirmationPayment,
    ForeignerProfile,
    PlatformFeeSettings,
    UserPayableItem,
    FurniturePackage, 
    FurniturePackageItem,
    PaymentTransaction, 
    PaymentTransactionItem,
    ServiceChangeRequest,
    ServiceChangeSettlementItem,
    WalletAccount,
    WalletTransaction,
    Payout,
    PayoutRequest,
    ForeignerInterest,
    MarketingResource
)


class PackageFeatureInline(admin.TabularInline):
    model = PackageFeature
    extra = 1
    fields = ['feature_text', 'order']
    ordering = ['order']
    sortable_field_name = 'order'


@admin.register(Package)
class PackageAdmin(admin.ModelAdmin):
    list_display = [
        'name',
        'level',
        'monthly_price_usd',
        'confirmation_fee_usd',
        'service_fee_percentage',
        'service_fee_amount_display',
        'affiliate_fee_percentage',
        'affiliate_fee_amount_display',
        'estimated_rent_usd',
        'estimated_deposit_months',
        'estimated_rental_deposit_display',
        'is_featured',
        'is_active',
        'order',
        'package_image_preview',
    ]
    list_filter = ['level', 'is_featured', 'is_active']
    search_fields = ['name', 'short_description', 'full_description', 'target_audience']
    prepopulated_fields = {'slug': ('name',)}
    list_editable = ['is_featured', 'is_active', 'order']
    ordering = ['order', 'monthly_price_usd']
    inlines = [PackageFeatureInline]

    fieldsets = (
        ('Basic Information', {
            'fields': (
                'name',
                'slug',
                'level',
                'monthly_price_usd',
                'image',
            )
        }),
        ('Descriptions', {
            'fields': (
                'short_description',
                'full_description',
                'target_audience',
            )
        }),
        ('Budget Breakdown', {
            'fields': (
                'housing_cost',
                'food_cost',
                'utilities_cost',
                'transport_cost',
                'support_cost',
                'leisure_cost',
                'misc_cost',
            )
        }),
        ('Service Charges & Affiliate', {
            'fields': (
                'confirmation_fee_usd',
                'service_fee_percentage',
                'affiliate_fee_percentage',
            ),
            'description': 'Service fee is calculated from the monthly package value. Affiliate fee is calculated from the service fee.'
        }),
        ('Estimated Rent & Deposit', {
            'fields': (
                'estimated_rent_usd',
                'estimated_deposit_months',
            ),
            'description': 'Used to show an estimated rental deposit. Actual deposit may vary depending on the selected property.'
        }),
        ('Display Settings', {
            'fields': (
                'is_featured',
                'is_active',
                'order',
            )
        }),
    )

    def package_image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="width:70px;height:50px;object-fit:cover;border-radius:8px;" />',
                obj.image.url
            )
        return "-"
    package_image_preview.short_description = 'Preview'

    def service_fee_amount_display(self, obj):
        return f"${obj.service_fee_amount}"
    service_fee_amount_display.short_description = 'Service Fee'

    def affiliate_fee_amount_display(self, obj):
        return f"${obj.affiliate_fee_amount}"
    affiliate_fee_amount_display.short_description = 'Affiliate Fee'

    def estimated_rental_deposit_display(self, obj):
        return f"${obj.estimated_rental_deposit_usd}"
    estimated_rental_deposit_display.short_description = 'Est. Deposit'


class ConfirmationPaymentInline(admin.TabularInline):
    model = ConfirmationPayment
    extra = 0
    fields = [
        'amount_usd',
        'payment_method',
        'payment_reference',
        'is_paid',
        'paid_at',
        'created_at',
    ]
    readonly_fields = ['paid_at', 'created_at']


@admin.register(ForeignerLead)
class ForeignerLeadAdmin(admin.ModelAdmin):
    list_display = [
        'full_name',
        'email',
        'country',
        'monthly_budget',
        'interested_package',
        'remote_worker',
        'is_confirmed_foreigner',
        'created_at',
    ]
    list_filter = [
        'monthly_budget',
        'is_confirmed_foreigner',
        'remote_worker',
        'country',
        'nationality',
        'created_at',
    ]
    search_fields = [
        'full_name',
        'email',
        'country',
        'nationality',
        'whatsapp_number',
        'message',
    ]
    list_editable = ['is_confirmed_foreigner']
    readonly_fields = ['created_at']
    ordering = ['-created_at']

    fieldsets = (
        ('Personal Details', {
            'fields': ('full_name', 'email', 'whatsapp_number', 'country', 'nationality')
        }),
        ('Travel & Budget Details', {
            'fields': (
                'expected_arrival_date',
                'duration_of_stay',
                'monthly_budget',
                'interested_package',
                'remote_worker',
            )
        }),
        ('Message & Status', {
            'fields': ('message', 'is_confirmed_foreigner', 'created_at')
        }),
    )

    actions = ['mark_as_confirmed', 'mark_as_not_confirmed']

    def mark_as_confirmed(self, request, queryset):
        updated = queryset.update(is_confirmed_foreigner=True)
        self.message_user(request, f"{updated} lead(s) marked as confirmed.")
    mark_as_confirmed.short_description = "Mark selected leads as confirmed"

    def mark_as_not_confirmed(self, request, queryset):
        updated = queryset.update(is_confirmed_foreigner=False)
        self.message_user(request, f"{updated} lead(s) marked as not confirmed.")
    mark_as_not_confirmed.short_description = "Mark selected leads as not confirmed"


@admin.register(ConsultationRequest)
class ConsultationRequestAdmin(admin.ModelAdmin):
    list_display = [
        'lead',
        'package',
        'preferred_contact_method',
        'preferred_date',
        'payment_status_badge',
        'created_at',
    ]
    list_filter = [
        'preferred_contact_method',
        'preferred_date',
        'created_at',
        'package',
    ]
    search_fields = [
        'lead__full_name',
        'lead__email',
        'notes',
    ]
    readonly_fields = ['created_at']
    ordering = ['-created_at']
    inlines = [ConfirmationPaymentInline]

    fieldsets = (
        ('Consultation Details', {
            'fields': ('lead', 'package', 'preferred_contact_method', 'preferred_date')
        }),
        ('Extra Notes', {
            'fields': ('notes',)
        }),
        ('System Info', {
            'fields': ('created_at',)
        }),
    )

    def payment_status_badge(self, obj):
        paid_exists = obj.confirmation_payments.filter(is_paid=True).exists()
        if paid_exists:
            return format_html(
                '<span style="background:#d1fae5;color:#065f46;padding:4px 10px;border-radius:999px;font-weight:600;">Paid</span>'
            )
        payment_exists = obj.confirmation_payments.exists()
        if payment_exists:
            return format_html(
                '<span style="background:#fef3c7;color:#92400e;padding:4px 10px;border-radius:999px;font-weight:600;">Pending</span>'
            )
        return format_html(
            '<span style="background:#e5e7eb;color:#374151;padding:4px 10px;border-radius:999px;font-weight:600;">No Payment</span>'
        )
    payment_status_badge.short_description = 'Confirmation Payment'


@admin.register(ConfirmationPayment)
class ConfirmationPaymentAdmin(admin.ModelAdmin):
    list_display = [
        'consultation',
        'lead_name',
        'amount_usd',
        'payment_method',
        'is_paid',
        'paid_at',
        'created_at',
    ]
    list_filter = ['is_paid', 'payment_method', 'created_at', 'paid_at']
    search_fields = [
        'consultation__lead__full_name',
        'consultation__lead__email',
        'payment_reference',
        'notes',
    ]
    readonly_fields = ['paid_at', 'created_at']
    ordering = ['-created_at']

    fieldsets = (
        ('Payment Details', {
            'fields': (
                'consultation',
                'amount_usd',
                'payment_method',
                'payment_reference',
                'is_paid',
                'paid_at',
            )
        }),
        ('Extra Notes', {
            'fields': ('notes',)
        }),
        ('System Info', {
            'fields': ('created_at',)
        }),
    )

    actions = ['mark_as_paid', 'mark_as_unpaid']

    def lead_name(self, obj):
        return obj.consultation.lead.full_name
    lead_name.short_description = 'Lead'

    def mark_as_paid(self, request, queryset):
        count = 0
        for payment in queryset:
            if not payment.is_paid:
                payment.is_paid = True
                payment.save()
                count += 1
        self.message_user(request, f"{count} payment(s) marked as paid.")
    mark_as_paid.short_description = "Mark selected payments as paid"

    def mark_as_unpaid(self, request, queryset):
        count = 0
        for payment in queryset:
            if payment.is_paid:
                payment.is_paid = False
                payment.save()
                count += 1
        self.message_user(request, f"{count} payment(s) marked as unpaid.")
    mark_as_unpaid.short_description = "Mark selected payments as unpaid"


@admin.register(ContactMessage)
class ContactMessageAdmin(admin.ModelAdmin):
    list_display = ['name', 'email', 'subject', 'created_at']
    list_filter = ['created_at']
    search_fields = ['name', 'email', 'subject', 'message']
    readonly_fields = ['created_at']
    ordering = ['-created_at']

    fieldsets = (
        ('Contact Details', {
            'fields': ('name', 'email', 'subject')
        }),
        ('Message', {
            'fields': ('message',)
        }),
        ('System Info', {
            'fields': ('created_at',)
        }),
    )

@admin.register(ForeignerProfile)
class ForeignerProfileAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'lead',
        'profile_image_preview_small',
        'status',
        'visit_stage',
        'is_public',
        'is_featured',
        'is_confirmed',
        'can_view_private_listings',
        'can_book_arrangements',
        'joined_at',
    ]

    list_editable = [
        'status',
        'visit_stage',
        'is_public',
        'is_featured',
        'is_confirmed',
        'can_view_private_listings',
        'can_book_arrangements',
    ]

    list_filter = [
        'status',
        'visit_stage',
        'is_public',
        'is_featured',
        'is_confirmed',
        'can_view_private_listings',
        'can_book_arrangements',
        'joined_at',
    ]

    search_fields = [
        'user__username',
        'user__email',
        'lead__full_name',
        'lead__email',
    ]

    readonly_fields = [
        'joined_at',
        'profile_image_preview',
    ]

    fieldsets = (
        ('User Link', {
            'fields': (
                'user',
                'lead',
            )
        }),

        ('Profile Image', {
            'fields': (
                'profile_image',
                'profile_image_preview',
            )
        }),

        ('Status, Visit Stage, Visibility & Permissions', {
            'fields': (
                'status',
                'visit_stage',
                'is_public',
                'is_featured',
                'is_confirmed',
                'can_view_private_listings',
                'can_book_arrangements',
            )
        }),

        ('System Info', {
            'fields': (
                'joined_at',
            )
        }),
    )

    def profile_image_preview(self, obj):
        if obj.profile_image:
            return format_html(
                '<img src="{}" style="width:150px; height:150px; object-fit:cover; border-radius:10px;" />',
                obj.profile_image.url
            )
        return "No Image"

    profile_image_preview.short_description = "Profile Image Preview"

    def profile_image_preview_small(self, obj):
        if obj.profile_image:
            return format_html(
                '<img src="{}" style="width:50px; height:50px; object-fit:cover; border-radius:50%;" />',
                obj.profile_image.url
            )
        return "—"

    profile_image_preview_small.short_description = "Image"


@admin.register(PlatformFeeSettings)
class PlatformFeeSettingsAdmin(admin.ModelAdmin):
    list_display = [
        'dating_partner_confirmation_fee_usd',
        'foreigner_featured_profile_fee_usd',
        'dating_partner_featured_profile_fee_usd',
        'service_partner_featured_account_fee_usd',

        # Rental Owner
        'rental_owner_featured_profile_fee_usd',
        'rental_owner_monthly_fee_percentage',

        # Hosting Partner
        'hosting_partner_featured_profile_fee_usd',
        'hosting_partner_commission_percentage',

        # Affiliate
        'affiliate_commission_percentage',

        'is_active',
        'updated_at',
    ]

    readonly_fields = ['updated_at']

    fieldsets = (
        ('Dating Partner Fees', {
            'fields': (
                'dating_partner_confirmation_fee_usd',
                'dating_partner_featured_profile_fee_usd',
            )
        }),

        ('Foreigner / Guest Fees', {
            'fields': (
                'foreigner_featured_profile_fee_usd',
            )
        }),

        ('Service Partner Fees', {
            'fields': (
                'service_partner_featured_account_fee_usd',
            )
        }),

        ('Rental Owner Fees', {
            'fields': (
                'rental_owner_featured_profile_fee_usd',
                'rental_owner_monthly_fee_percentage',
            ),
            'description': (
                'Set rental owner featured listing fee and the monthly rental commission '
                'percentage charged by Ensolanka.'
            )
        }),

        ('Hosting Partner Fees / Commissions', {
            'fields': (
                'hosting_partner_featured_profile_fee_usd',
                'hosting_partner_commission_percentage',
            ),
            'description': (
                'Set the optional featured listing fee for Hosting Partners and the commission '
                'percentage charged by Ensolanka from confirmed hosting event bookings.'
            )
        }),

        ('Affiliate Fees / Commissions', {
            'fields': (
                'affiliate_commission_percentage',
            ),
            'description': (
                'Set the commission percentage paid to affiliates from eligible Guest fees, '
                'such as the confirmation fee and one-time service fee.'
            )
        }),

        ('Status', {
            'fields': (
                'is_active',
                'updated_at',
            )
        }),
    )

    def has_add_permission(self, request):
        return not PlatformFeeSettings.objects.exists()

@admin.register(UserPayableItem)
class UserPayableItemAdmin(admin.ModelAdmin):
    list_display = [
        'user',
        'profile_type',
        'payment_for',
        'title',
        'amount_state',
        'amount_usd',
        'payment_status',
        'is_optional',
        'is_active',
        'due_date',
        'effective_from',
        'paid_at',
        'updated_at',
    ]

    list_filter = [
        'profile_type',
        'payment_for',
        'amount_state',
        'payment_status',
        'is_optional',
        'is_active',
    ]

    search_fields = [
        'user__username',
        'user__email',
        'title',
        'description',
        'notes',
    ]

    list_editable = [
        'amount_state',
        'amount_usd',
        'payment_status',
        'is_optional',
        'is_active',
        'due_date',
        'effective_from',
    ]

    readonly_fields = [
        'created_at',
        'updated_at',
        'paid_at',
    ]

    ordering = ['payment_status', 'due_date', 'created_at']

    fieldsets = (
        ('User & Profile', {
            'fields': (
                'user',
                'profile_type',
            )
        }),
        ('Payment Details', {
            'fields': (
                'payment_for',
                'title',
                'description',
                'amount_state',
                'amount_usd',
                'payment_status',
                'is_optional',
                'is_active',
            )
        }),
        ('Schedule', {
            'fields': (
                'due_date',
                'effective_from',
                'paid_at',
            )
        }),
        ('Extra Notes', {
            'fields': (
                'notes',
            )
        }),
        ('System Info', {
            'fields': (
                'created_at',
                'updated_at',
            )
        }),
    )

class FurniturePackageItemInline(admin.TabularInline):
    model = FurniturePackageItem
    extra = 1
    fields = ('item_name', 'quantity', 'notes', 'order')
    ordering = ('order', 'id')


@admin.register(FurniturePackage)
class FurniturePackageAdmin(admin.ModelAdmin):
    list_display = (
        'name',
        'level',
        'monthly_rental_usd',
        'deposit_months',
        'calculated_deposit_usd',
        'total_purchase_value_usd',
        'is_featured',
        'is_active',
        'order',
    )
    list_filter = ('level', 'is_featured', 'is_active')
    search_fields = ('name', 'short_description', 'full_description')
    prepopulated_fields = {'slug': ('name',)}
    readonly_fields = ('calculated_deposit_usd',)

    fieldsets = (
        ('Basic Information', {
            'fields': (
                'name',
                'slug',
                'level',
                'image',
                'is_featured',
                'is_active',
                'order',
            )
        }),
        ('Descriptions', {
            'fields': ('short_description', 'full_description')
        }),
        ('Pricing', {
            'fields': (
                'monthly_rental_usd',
                'deposit_months',
                'total_purchase_value_usd',
                'calculated_deposit_usd',
            )
        }),
    )


@admin.register(FurniturePackageItem)
class FurniturePackageItemAdmin(admin.ModelAdmin):
    list_display = (
        'item_name',
        'furniture_package',
        'quantity',
        'order',
    )
    list_filter = ('furniture_package',)
    search_fields = ('item_name', 'notes', 'furniture_package__name')
    ordering = ('furniture_package', 'order', 'id')

class PaymentTransactionItemInline(admin.TabularInline):
    model = PaymentTransactionItem
    extra = 0
    autocomplete_fields = ['payable_item']
    fields = ['payable_item', 'amount_usd']
    readonly_fields = []
    show_change_link = True


@admin.register(PaymentTransaction)
class PaymentTransactionAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'user',
        'profile_type',
        'payment_method',
        'gateway_transaction_id',
        'total_amount_usd',
        'status',
        'created_at',
    ]
    list_filter = [
        'profile_type',
        'payment_method',
        'status',
        'created_at',
    ]
    search_fields = [
        'id',
        'user__username',
        'user__email',
        'profile_type',
        'payment_method',
        'gateway_transaction_id',
    ]
    readonly_fields = ['created_at']
    inlines = [PaymentTransactionItemInline]

    fieldsets = (
        ('Transaction Info', {
            'fields': (
                'user',
                'profile_type',
                'payment_method',
                'gateway_transaction_id',
                'status',
                'total_amount_usd',
                'created_at',
            )
        }),
    )


@admin.register(PaymentTransactionItem)
class PaymentTransactionItemAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'transaction',
        'get_user',
        'get_profile_type',
        'payable_item',
        'amount_usd',
    ]
    list_filter = [
        'transaction__profile_type',
        'transaction__payment_method',
        'transaction__status',
        'transaction__created_at',
    ]
    search_fields = [
        'transaction__id',
        'transaction__user__username',
        'transaction__user__email',
        'payable_item__title',
        'payable_item__payment_for',
    ]
    autocomplete_fields = ['transaction', 'payable_item']

    def get_user(self, obj):
        return obj.transaction.user
    get_user.short_description = 'User'
    get_user.admin_order_field = 'transaction__user'

    def get_profile_type(self, obj):
        return obj.transaction.profile_type
    get_profile_type.short_description = 'Profile Type'
    get_profile_type.admin_order_field = 'transaction__profile_type'

class ServiceChangeSettlementItemInline(admin.TabularInline):
    model = ServiceChangeSettlementItem
    extra = 0
    fields = [
        'item_type',
        'title',
        'amount_usd',
        'is_deduction',
        'description',
        'created_at',
    ]
    readonly_fields = ['created_at']
    show_change_link = True


class WalletTransactionInline(admin.TabularInline):
    model = WalletTransaction
    extra = 0
    fields = [
        'transaction_type',
        'status',
        'title',
        'amount_usd',
        'is_credit',
        'reference_code',
        'created_at',
    ]
    readonly_fields = ['created_at']
    show_change_link = True


@admin.register(ServiceChangeRequest)
class ServiceChangeRequestAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'user',
        'profile_type',
        'request_type',
        'status',
        'admin_approved',
        'approved_by',
        'requested_at',
        'reviewed_at',
        'completed_at',
    ]
    list_filter = [
        'profile_type',
        'request_type',
        'status',
        'admin_approved',
        'requested_at',
        'reviewed_at',
        'completed_at',
    ]
    search_fields = [
        'id',
        'user__username',
        'user__email',
        'user_reason',
        'admin_notes',
        'current_property__title',
        'current_package__name',
        'requested_new_package__name',
    ]
    autocomplete_fields = [
        'user',
        'foreigner_profile',
        'approved_by',
        'current_property',
        'current_furniture_package',
        'current_package',
        'requested_new_package',
    ]
    readonly_fields = [
        'requested_at',
        'reviewed_at',
        'completed_at',
    ]
    inlines = [ServiceChangeSettlementItemInline]

    fieldsets = (
        ('Basic Info', {
            'fields': (
                'user',
                'profile_type',
                'foreigner_profile',
                'request_type',
                'status',
            )
        }),
        ('Approval', {
            'fields': (
                'admin_approved',
                'approved_by',
                'admin_notes',
            )
        }),
        ('Current / Requested Service Details', {
            'fields': (
                'current_property',
                'current_furniture_package',
                'current_package',
                'requested_new_package',
            )
        }),
        ('Reasons / Notes', {
            'fields': (
                'user_reason',
            )
        }),
        ('Timestamps', {
            'fields': (
                'requested_at',
                'reviewed_at',
                'completed_at',
            )
        }),
    )


@admin.register(ServiceChangeSettlementItem)
class ServiceChangeSettlementItemAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'request',
        'item_type',
        'title',
        'amount_usd',
        'is_deduction',
        'created_at',
    ]
    list_filter = [
        'item_type',
        'is_deduction',
        'created_at',
    ]
    search_fields = [
        'id',
        'request__user__username',
        'request__user__email',
        'title',
        'description',
    ]
    autocomplete_fields = ['request']
    readonly_fields = ['created_at']


@admin.register(WalletAccount)
class WalletAccountAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'user',
        'profile_type',
        'balance_usd',
        'is_active',
        'created_at',
        'updated_at',
    ]
    list_filter = [
        'profile_type',
        'is_active',
        'created_at',
        'updated_at',
    ]
    search_fields = [
        'id',
        'user__username',
        'user__email',
    ]
    autocomplete_fields = ['user']
    readonly_fields = ['created_at', 'updated_at']
    inlines = [WalletTransactionInline]


@admin.register(WalletTransaction)
class WalletTransactionAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'wallet',
        'get_user',
        'get_profile_type',
        'transaction_type',
        'status',
        'title',
        'amount_usd',
        'is_credit',
        'reference_code',
        'created_at',
    ]
    list_filter = [
        'transaction_type',
        'status',
        'is_credit',
        'wallet__profile_type',
        'created_at',
    ]
    search_fields = [
        'id',
        'wallet__user__username',
        'wallet__user__email',
        'title',
        'description',
        'reference_code',
        'admin_notes',
        'related_payable_item__title',
    ]
    autocomplete_fields = [
        'wallet',
        'related_payable_item',
        'related_change_request',
    ]
    readonly_fields = ['created_at']

    def get_user(self, obj):
        return obj.wallet.user
    get_user.short_description = 'User'
    get_user.admin_order_field = 'wallet__user'

    def get_profile_type(self, obj):
        return obj.wallet.profile_type
    get_profile_type.short_description = 'Profile Type'
    get_profile_type.admin_order_field = 'wallet__profile_type'


@admin.register(Payout)
class PayoutAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'user',
        'profile_type',
        'payout_type',
        'amount_usd',
        'status',
        'requested_by_user',
        'reference_code',
        'approved_at',
        'paid_at',
        'created_at',
    ]
    list_filter = [
        'profile_type',
        'payout_type',
        'status',
        'requested_by_user',
        'created_at',
        'approved_at',
        'paid_at',
    ]
    search_fields = [
        'id',
        'user__username',
        'user__email',
        'title',
        'description',
        'reference_code',
        'admin_notes',
    ]
    autocomplete_fields = [
        'user',
        'foreigner_profile',
        'rental_owner',
        'wallet',
        'related_payable_item',
        'related_change_request',
    ]
    readonly_fields = ['created_at', 'approved_at', 'paid_at']

    fieldsets = (
        ('Basic Info', {
            'fields': (
                'user',
                'profile_type',
                'payout_type',
                'status',
                'requested_by_user',
            )
        }),
        ('Linked Profiles / Wallet', {
            'fields': (
                'foreigner_profile',
                'rental_owner',
                'wallet',
            )
        }),
        ('Amounts & References', {
            'fields': (
                'amount_usd',
                'title',
                'description',
                'reference_code',
            )
        }),
        ('Relations', {
            'fields': (
                'related_payable_item',
                'related_change_request',
            )
        }),
        ('Admin / Timing', {
            'fields': (
                'admin_notes',
                'approved_at',
                'paid_at',
                'created_at',
            )
        }),
    )


@admin.register(PayoutRequest)
class PayoutRequestAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'user',
        'profile_type',
        'request_type',
        'amount_usd',
        'status',
        'admin_approved',
        'approved_by',
        'requested_at',
        'reviewed_at',
        'completed_at',
    ]
    list_filter = [
        'profile_type',
        'request_type',
        'status',
        'admin_approved',
        'requested_at',
        'reviewed_at',
        'completed_at',
    ]
    search_fields = [
        'id',
        'user__username',
        'user__email',
        'user_reason',
        'admin_notes',
        'reference_code',
    ]
    autocomplete_fields = [
        'user',
        'wallet',
        'approved_by',
        'related_payout',
    ]
    readonly_fields = [
        'requested_at',
        'reviewed_at',
        'completed_at',
    ]

    fieldsets = (
        ('Basic Info', {
            'fields': (
                'user',
                'profile_type',
                'request_type',
                'wallet',
                'amount_usd',
                'status',
            )
        }),
        ('Approval', {
            'fields': (
                'admin_approved',
                'approved_by',
                'admin_notes',
                'related_payout',
            )
        }),
        ('Request Details', {
            'fields': (
                'user_reason',
                'reference_code',
            )
        }),
        ('Timestamps', {
            'fields': (
                'requested_at',
                'reviewed_at',
                'completed_at',
            )
        }),
    )

@admin.register(ForeignerInterest)
class ForeignerInterestAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'dating_partner_name',
        'foreigner_name',
        'status',
        'created_at',
    ]
    list_filter = [
        'status',
        'created_at',
    ]
    search_fields = [
        'dating_partner__full_name',
        'dating_partner__display_name',
        'dating_partner__user__username',
        'foreigner__user__username',
        'foreigner__lead__full_name',
        'foreigner__lead__email',
        'message',
    ]
    autocomplete_fields = [
        'dating_partner',
        'foreigner',
    ]
    readonly_fields = [
        'created_at',
    ]
    ordering = ['-created_at']

    fieldsets = (
        ('Interest Details', {
            'fields': (
                'dating_partner',
                'foreigner',
                'status',
            )
        }),
        ('Message', {
            'fields': (
                'message',
            )
        }),
        ('System Info', {
            'fields': (
                'created_at',
            )
        }),
    )

    def dating_partner_name(self, obj):
        return obj.dating_partner.display_name or obj.dating_partner.full_name
    dating_partner_name.short_description = 'Dating Partner'
    dating_partner_name.admin_order_field = 'dating_partner__full_name'

    def foreigner_name(self, obj):
        if obj.foreigner.lead and obj.foreigner.lead.full_name:
            return obj.foreigner.lead.full_name
        if obj.foreigner.user.get_full_name():
            return obj.foreigner.user.get_full_name()
        return obj.foreigner.user.username
    foreigner_name.short_description = 'Guest'
    foreigner_name.admin_order_field = 'foreigner__user__username'


@admin.register(MarketingResource)
class MarketingResourceAdmin(admin.ModelAdmin):
    list_display = (
        'title',
        'target_audience',
        'language',
        'has_full_brochure',
        'has_summary_overview',
        'has_presentation',
        'has_video',
        'has_audio',
        'has_digital_nomad_process',
        'has_digital_nomad_presentation',
        'has_digital_nomad_audio',
        'is_active',
        'created_at',
    )

    list_filter = (
        'target_audience',
        'language',
        'is_active',
        'created_at',
    )

    search_fields = (
        'title',
        'target_audience',
        'language',
    )

    readonly_fields = (
        'created_at',
        'updated_at',
        'full_brochure_preview',
        'summary_overview_preview',
        'presentation_preview',
        'video_preview',
        'audio_preview',
        'digital_nomad_process_preview',
        'digital_nomad_presentation_preview',
        'digital_nomad_audio_preview',
    )

    fieldsets = (
        ('Basic Info', {
            'fields': (
                'target_audience',
                'language',
                'title',
                'is_active',
            )
        }),

        ('Main Information Center Files', {
            'fields': (
                'full_brochure_pdf',
                'full_brochure_preview',
                'summary_overview_pdf',
                'summary_overview_preview',
                'presentation_pdf',
                'presentation_preview',
            ),
            'description': 'Upload the general full brochure, summary overview, and presentation PDF files.'
        }),

        ('Main Media Files & Links', {
            'fields': (
                'video_link',
                'video_preview',
                'audio_file',
                'audio_preview',
            ),
            'description': 'Add a YouTube/Vimeo video link and upload the main MP3 audio guide.'
        }),

        ('Digital Nomad Visa Process Resources', {
            'fields': (
                'digital_nomad_visa_process_pdf',
                'digital_nomad_process_preview',
                'digital_nomad_visa_presentation_pdf',
                'digital_nomad_presentation_preview',
                'digital_nomad_visa_audio_file',
                'digital_nomad_audio_preview',
            ),
            'description': 'Upload the Digital Nomad Visa process document, illustrative presentation, and audio explainer.'
        }),

        ('Timestamps', {
            'fields': (
                'created_at',
                'updated_at',
            ),
            'classes': ('collapse',)
        }),
    )

    # -----------------------------
    # List display indicators
    # -----------------------------

    def has_full_brochure(self, obj):
        return bool(obj.full_brochure_pdf)
    has_full_brochure.boolean = True
    has_full_brochure.short_description = 'Brochure'

    def has_summary_overview(self, obj):
        return bool(obj.summary_overview_pdf)
    has_summary_overview.boolean = True
    has_summary_overview.short_description = 'Summary'

    def has_presentation(self, obj):
        return bool(obj.presentation_pdf)
    has_presentation.boolean = True
    has_presentation.short_description = 'Presentation'

    def has_video(self, obj):
        return bool(obj.video_link)
    has_video.boolean = True
    has_video.short_description = 'Video'

    def has_audio(self, obj):
        return bool(obj.audio_file)
    has_audio.boolean = True
    has_audio.short_description = 'Audio'

    def has_digital_nomad_process(self, obj):
        return bool(obj.digital_nomad_visa_process_pdf)
    has_digital_nomad_process.boolean = True
    has_digital_nomad_process.short_description = 'DN Visa Doc'

    def has_digital_nomad_presentation(self, obj):
        return bool(obj.digital_nomad_visa_presentation_pdf)
    has_digital_nomad_presentation.boolean = True
    has_digital_nomad_presentation.short_description = 'DN Visa Slides'

    def has_digital_nomad_audio(self, obj):
        return bool(obj.digital_nomad_visa_audio_file)
    has_digital_nomad_audio.boolean = True
    has_digital_nomad_audio.short_description = 'DN Visa Audio'

    # -----------------------------
    # Preview links - Main files
    # -----------------------------

    def full_brochure_preview(self, obj):
        if obj.full_brochure_pdf:
            return format_html(
                '<a href="{}" target="_blank">📄 View Full Brochure PDF</a>',
                obj.full_brochure_pdf.url
            )
        return "No full brochure uploaded"
    full_brochure_preview.short_description = 'Full Brochure Preview'

    def summary_overview_preview(self, obj):
        if obj.summary_overview_pdf:
            return format_html(
                '<a href="{}" target="_blank">📘 View Summary Overview PDF</a>',
                obj.summary_overview_pdf.url
            )
        return "No summary overview uploaded"
    summary_overview_preview.short_description = 'Summary Overview Preview'

    def presentation_preview(self, obj):
        if obj.presentation_pdf:
            return format_html(
                '<a href="{}" target="_blank">📊 View Presentation PDF</a>',
                obj.presentation_pdf.url
            )
        return "No presentation uploaded"
    presentation_preview.short_description = 'Presentation Preview'

    def video_preview(self, obj):
        if obj.video_link:
            return format_html(
                '<a href="{}" target="_blank">▶ Watch Video</a>',
                obj.video_link
            )
        return "No video link"
    video_preview.short_description = 'Video Preview'

    def audio_preview(self, obj):
        if obj.audio_file:
            return format_html(
                '''
                <div style="min-width: 280px;">
                    <audio controls preload="metadata" style="width: 100%; max-width: 360px;">
                        <source src="{}" type="audio/mpeg">
                        Your browser does not support the audio element.
                    </audio>
                    <br>
                    <a href="{}" target="_blank" download>🎧 Download Audio File</a>
                </div>
                ''',
                obj.audio_file.url,
                obj.audio_file.url
            )
        return "No audio uploaded"
    audio_preview.short_description = 'Audio Preview'

    # -----------------------------
    # Preview links - Digital Nomad Visa resources
    # -----------------------------

    def digital_nomad_process_preview(self, obj):
        if obj.digital_nomad_visa_process_pdf:
            return format_html(
                '<a href="{}" target="_blank">📄 View Digital Nomad Visa Process Document</a>',
                obj.digital_nomad_visa_process_pdf.url
            )
        return "No Digital Nomad Visa process document uploaded"
    digital_nomad_process_preview.short_description = 'DN Visa Process Preview'

    def digital_nomad_presentation_preview(self, obj):
        if obj.digital_nomad_visa_presentation_pdf:
            return format_html(
                '<a href="{}" target="_blank">📊 View Digital Nomad Visa Presentation</a>',
                obj.digital_nomad_visa_presentation_pdf.url
            )
        return "No Digital Nomad Visa presentation uploaded"
    digital_nomad_presentation_preview.short_description = 'DN Visa Presentation Preview'

    def digital_nomad_audio_preview(self, obj):
        if obj.digital_nomad_visa_audio_file:
            return format_html(
                '''
                <div style="min-width: 280px;">
                    <audio controls preload="metadata" style="width: 100%; max-width: 360px;">
                        <source src="{}" type="audio/mpeg">
                        Your browser does not support the audio element.
                    </audio>
                    <br>
                    <a href="{}" target="_blank" download>🎧 Download Digital Nomad Visa Audio</a>
                </div>
                ''',
                obj.digital_nomad_visa_audio_file.url,
                obj.digital_nomad_visa_audio_file.url
            )
        return "No Digital Nomad Visa audio uploaded"
    digital_nomad_audio_preview.short_description = 'DN Visa Audio Preview'