from django.contrib import admin

from .models import (
    AffiliateProfile,
    AffiliateGuestReferral,
    AffiliateCommission,
    AffiliatePayoutRequest,
    AffiliateMarketingResource,
    AffiliateBusinessCard,
    AffiliateResourceRequest,
    AffiliateTrainingResource,
)

from django.utils.html import format_html
from django.db.models import Q


@admin.register(AffiliateProfile)
class AffiliateProfileAdmin(admin.ModelAdmin):
    list_display = (
        'full_name',
        'affiliate_code',
        'phone',
        'country',
        'status',
        'is_active',
        'total_earned_usd',
        'total_paid_usd',
        'created_at',
    )
    list_filter = ('status', 'is_active', 'country', 'created_at')
    search_fields = ('full_name', 'affiliate_code', 'phone', 'user__email')
    readonly_fields = ('affiliate_code', 'total_earned_usd', 'total_paid_usd', 'created_at', 'updated_at')


@admin.register(AffiliateGuestReferral)
class AffiliateGuestReferralAdmin(admin.ModelAdmin):
    list_display = (
        'affiliate',
        'guest_name',
        'guest_email',
        'selected_package_name',
        'total_possible_commission_usd',
        'total_earned_commission_usd',
        'status',
        'created_at',
    )
    list_filter = ('status', 'created_at')
    search_fields = (
        'affiliate__full_name',
        'affiliate__affiliate_code',
        'guest_name',
        'guest_email',
        'guest_phone',
    )
    readonly_fields = ('created_at', 'updated_at')


@admin.register(AffiliateCommission)
class AffiliateCommissionAdmin(admin.ModelAdmin):
    list_display = (
        'affiliate',
        'commission_for',
        'source_amount_usd',
        'commission_percentage',
        'commission_amount_usd',
        'status',
        'created_at',
    )
    list_filter = ('commission_for', 'status', 'created_at')
    search_fields = ('affiliate__full_name', 'affiliate__affiliate_code')
    readonly_fields = ('created_at',)


@admin.register(AffiliatePayoutRequest)
class AffiliatePayoutRequestAdmin(admin.ModelAdmin):
    list_display = (
        'affiliate',
        'amount_usd',
        'status',
        'requested_at',
        'processed_at',
    )
    list_filter = ('status', 'requested_at')
    search_fields = ('affiliate__full_name', 'affiliate__affiliate_code')
    readonly_fields = ('requested_at',)



class AffiliateBusinessCardAdmin(admin.ModelAdmin):
    list_display = ('id', 'affiliate_profile', 'preview_referral_link', 'created_at', 'is_active', 'card_preview')
    list_filter = ('is_active', 'created_at', 'affiliate_profile')
    search_fields = ('affiliate_profile__full_name', 'affiliate_profile__affiliate_code', 'referral_link')
    readonly_fields = ('created_at', 'updated_at', 'qr_code_preview', 'card_preview_large')
    fieldsets = (
        ('Affiliate Info', {
            'fields': ('affiliate_profile', 'referral_link', 'is_active')
        }),
        ('Generated Images', {
            'fields': ('qr_code_image', 'business_card_image', 'qr_code_preview', 'card_preview_large')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    def preview_referral_link(self, obj):
        return format_html('<a href="{}" target="_blank">{}</a>', obj.referral_link, obj.referral_link[:50])
    preview_referral_link.short_description = 'Referral Link'

    def qr_code_preview(self, obj):
        if obj.qr_code_image and hasattr(obj.qr_code_image, 'url'):
            return format_html('<img src="{}" width="100" height="100" />', obj.qr_code_image.url)
        return "No QR code"
    qr_code_preview.short_description = 'QR Code Preview'

    def card_preview(self, obj):
        if obj.business_card_image and hasattr(obj.business_card_image, 'url'):
            return format_html('<img src="{}" width="80" />', obj.business_card_image.url)
        return "No card"
    card_preview.short_description = 'Card'

    def card_preview_large(self, obj):
        if obj.business_card_image and hasattr(obj.business_card_image, 'url'):
            return format_html('<img src="{}" width="400" />', obj.business_card_image.url)
        return "No card image"
    card_preview_large.short_description = 'Business Card Preview'

    def delete_queryset(self, request, queryset):
        # Delete image files before deleting the records
        for obj in queryset:
            obj.delete_qr_and_card_files()
        super().delete_queryset(request, queryset)

    def delete_model(self, request, obj):
        obj.delete_qr_and_card_files()
        super().delete_model(request, obj)

admin.site.register(AffiliateBusinessCard, AffiliateBusinessCardAdmin)


@admin.register(AffiliateMarketingResource)
class AffiliateMarketingResourceAdmin(admin.ModelAdmin):
    list_display = (
        'title',
        'affiliate_profile',
        'language',
        'has_full_pdf',
        'has_summary_overview',
        'has_presentation',
        'is_active',
        'created_at',
    )

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

    search_fields = (
        'title',
        'affiliate_profile__full_name',
        'affiliate_profile__affiliate_code',
    )

    readonly_fields = (
        'created_at',
        'updated_at',
        'full_pdf_preview',
        'summary_overview_preview',
        'presentation_preview',
    )

    fieldsets = (
        ('Affiliate & Document', {
            'fields': (
                'affiliate_profile',
                'title',
                'language',
                'is_active',
            )
        }),

        ('PDF Files', {
            'fields': (
                'full_pdf_file',
                'full_pdf_preview',
                'summary_overview_pdf',
                'summary_overview_preview',
                'presentation_pdf',
                'presentation_preview',
                'description',
            ),
            'description': 'Upload the custom full brochure, summary overview, and presentation PDF files for this affiliate.'
        }),

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

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

    def has_full_pdf(self, obj):
        return bool(obj.full_pdf_file)
    has_full_pdf.boolean = True
    has_full_pdf.short_description = 'Full PDF'

    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'

    # -----------------------------
    # Preview links
    # -----------------------------

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

    def summary_overview_preview(self, obj):
        if obj.summary_overview_pdf:
            return format_html(
                '<a href="{}" target="_blank">📘 View Summary Overview</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</a>',
                obj.presentation_pdf.url
            )
        return "No presentation uploaded"
    presentation_preview.short_description = 'Presentation Preview'

@admin.register(AffiliateResourceRequest)
class AffiliateResourceRequestAdmin(admin.ModelAdmin):
    list_display = ('affiliate_profile', 'requested_languages_display', 'status', 'request_date', 'responded_at')
    list_filter = ('status', 'request_date')
    search_fields = ('affiliate_profile__full_name', 'affiliate_profile__affiliate_code')
    readonly_fields = ('request_date', 'created_at', 'updated_at')
    fieldsets = (
        ('Request Info', {
            'fields': ('affiliate_profile', 'requested_languages', 'request_date', 'status')
        }),
        ('Response', {
            'fields': ('response_message', 'responded_at', 'responded_by', 'admin_notes')
        }),
        ('Timestamps', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    def requested_languages_display(self, obj):
        return ", ".join(obj.requested_languages)
    requested_languages_display.short_description = "Languages"

@admin.register(AffiliateTrainingResource)
class AffiliateTrainingResourceAdmin(admin.ModelAdmin):
    list_display = (
        'title',
        'language',
        'has_full_playbook',
        'has_summary_overview',
        'has_audio_guide',
        'has_youtube_video',
        'is_active',
        'created_at',
    )

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

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

    readonly_fields = (
        'created_at',
        'updated_at',
        'full_playbook_preview',
        'summary_overview_preview',
        'audio_guide_preview',
        'youtube_video_preview',
    )

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

        ('Training Documents', {
            'fields': (
                'full_playbook_pdf',
                'full_playbook_preview',
                'summary_overview_pdf',
                'summary_overview_preview',
            ),
            'description': 'Upload the full training playbook and summary overview PDF files.'
        }),

        ('Audio Training', {
            'fields': (
                'audio_guide_file',
                'audio_guide_preview',
            ),
            'description': 'Upload the MP3 audio training guide.'
        }),

        ('Video Training', {
            'fields': (
                'youtube_video_link',
                'youtube_video_preview',
            ),
            'description': 'Add the YouTube video training link.'
        }),

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

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

    def has_full_playbook(self, obj):
        return bool(obj.full_playbook_pdf)
    has_full_playbook.boolean = True
    has_full_playbook.short_description = 'Full Playbook'

    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_audio_guide(self, obj):
        return bool(obj.audio_guide_file)
    has_audio_guide.boolean = True
    has_audio_guide.short_description = 'Audio'

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

    # -----------------------------
    # Preview fields
    # -----------------------------

    def full_playbook_preview(self, obj):
        if obj.full_playbook_pdf:
            return format_html(
                '<a href="{}" target="_blank">📄 View Full Playbook PDF</a>',
                obj.full_playbook_pdf.url
            )
        return "No full playbook uploaded"
    full_playbook_preview.short_description = 'Full Playbook 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 audio_guide_preview(self, obj):
        if obj.audio_guide_file:
            return format_html(
                '''
                <div style="min-width: 300px;">
                    <audio controls preload="metadata" style="width: 100%; max-width: 380px;">
                        <source src="{}" type="audio/mpeg">
                        Your browser does not support the audio element.
                    </audio>
                    <br>
                    <a href="{}" target="_blank" download>🎧 Download Audio Guide</a>
                </div>
                ''',
                obj.audio_guide_file.url,
                obj.audio_guide_file.url
            )
        return "No audio guide uploaded"
    audio_guide_preview.short_description = 'Audio Guide Preview'

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