"""
Admin interface for managing installment payments
Add this to your shop/admin.py
"""

from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.db.models import Q

from .models import InstallmentSchedule, ScheduledPayment, RecurringPaymentToken


class ScheduledPaymentInline(admin.TabularInline):
    """Display scheduled payments inline within installment schedule"""
    model = ScheduledPayment
    extra = 0
    readonly_fields = (
        'installment_number', 'amount', 'due_date', 'scheduled_date',
        'status', 'transaction_reference', 'processed_at', 'retry_count'
    )
    fields = (
        'installment_number', 'amount', 'due_date', 'status',
        'retry_count', 'transaction_reference'
    )
    can_delete = False
    
    def has_add_permission(self, request, obj=None):
        return False


@admin.register(RecurringPaymentToken)
class RecurringPaymentTokenAdmin(admin.ModelAdmin):
    """Admin interface for managing saved payment tokens"""
    
    list_display = (
        'user_link', 'card_display', 'is_authorized_badge', 
        'is_active_badge', 'last_used', 'created_at'
    )
    list_filter = ('is_authorized', 'is_active', 'created_at', 'gateway')
    search_fields = ('user__username', 'user__email', 'card_last_four')
    readonly_fields = ('created_at', 'flutterwave_token')
    
    fields = (
        'user', 'card_brand', 'card_last_four', 'flutterwave_token',
        'is_authorized', 'authorized_at', 'is_active', 'last_used',
        'gateway', 'created_at'
    )
    
    def user_link(self, obj):
        """Link to user admin"""
        url = reverse('admin:auth_user_change', args=[obj.user.id])
        return format_html('<a href="{}">{}</a>', url, obj.user.username)
    user_link.short_description = _('User')
    
    def card_display(self, obj):
        """Display card brand and last 4 digits"""
        return f"{obj.card_brand} ****{obj.card_last_four}"
    card_display.short_description = _('Card')
    
    def is_authorized_badge(self, obj):
        """Color-coded authorization status"""
        if obj.is_authorized:
            return format_html(
                '<span style="color: green;"><strong>✓ Authorized</strong></span>'
            )
        return format_html(
            '<span style="color: orange;"><strong>⚠ Pending</strong></span>'
        )
    is_authorized_badge.short_description = _('Authorization')
    
    def is_active_badge(self, obj):
        """Color-coded active status"""
        if obj.is_active:
            return format_html(
                '<span style="color: green;"><strong>✓ Active</strong></span>'
            )
        return format_html(
            '<span style="color: red;"><strong>✗ Inactive</strong></span>'
        )
    is_active_badge.short_description = _('Status')
    
    def has_add_permission(self, request):
        """Tokens are created during payment setup, not manually"""
        return False
    
    def has_delete_permission(self, request, obj=None):
        """Require special permission to delete tokens"""
        return request.user.is_superuser


@admin.register(InstallmentSchedule)
class InstallmentScheduleAdmin(admin.ModelAdmin):
    """Admin interface for managing installment schedules"""
    
    list_display = (
        'order_link', 'customer_link', 'status_badge', 'progress_display',
        'monthly_amount', 'next_payment_badge', 'failed_attempts_badge'
    )
    list_filter = ('status', 'auto_retry', 'created_at', 'start_date')
    search_fields = ('order__id', 'order__user__email', 'order__user__username')
    
    fields = (
        'order', 'payment_token', 'status',
        'installment_amount', 'total_installments', 'paid_installments',
        'failed_attempts', 'auto_retry', 'max_retries',
        'start_date', 'next_payment_date', 'final_payment_date',
        'created_at', 'updated_at'
    )
    
    readonly_fields = (
        'order', 'created_at', 'updated_at'
    )
    
    inlines = [ScheduledPaymentInline]
    
    def order_link(self, obj):
        """Link to order admin"""
        url = reverse('admin:shop_order_change', args=[obj.order.id])
        return format_html(
            '<a href="{}">#Order {}</a>',
            url, obj.order.id
        )
    order_link.short_description = _('Order')
    
    def customer_link(self, obj):
        """Link to customer admin"""
        user = obj.order.user
        url = reverse('admin:auth_user_change', args=[user.id])
        return format_html('<a href="{}">{}</a>', url, user.username)
    customer_link.short_description = _('Customer')
    
    def status_badge(self, obj):
        """Color-coded status badge"""
        colors = {
            'active': 'green',
            'completed': 'blue',
            'suspended': 'red',
            'cancelled': 'gray',
        }
        color = colors.get(obj.status, 'gray')
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            color,
            obj.get_status_display()
        )
    status_badge.short_description = _('Status')
    
    def progress_display(self, obj):
        """Visual progress bar"""
        percent = int((obj.paid_installments / obj.total_installments) * 100)
        return format_html(
            '<div style="width:100px; background: #e0e0e0; border-radius: 3px;">'
            '<div style="width:{}%; background: green; height: 20px; '
            'text-align: center; color: white; font-size: 11px; line-height: 20px;">'
            '{}%</div></div> {}/{}',
            percent, percent, obj.paid_installments, obj.total_installments
        )
    progress_display.short_description = _('Progress')
    
    def monthly_amount(self, obj):
        """Display monthly amount"""
        return f"${obj.installment_amount:.2f}"
    monthly_amount.short_description = _('Monthly')
    
    def next_payment_badge(self, obj):
        """Next payment date with status"""
        from django.utils import timezone
        import datetime
        
        today = timezone.now().date()
        days_until = (obj.next_payment_date - today).days
        
        if days_until < 0:
            return format_html(
                '<span style="color: red;"><strong>⚠ OVERDUE</strong></span> '
                '({})', obj.next_payment_date
            )
        elif days_until == 0:
            return format_html(
                '<span style="color: orange;"><strong>Today</strong></span>'
            )
        elif days_until <= 3:
            return format_html(
                '<span style="color: orange;">In {} days</span>',
                days_until
            )
        else:
            return format_html('{} days', days_until)
    
    next_payment_badge.short_description = _('Next Payment')
    
    def failed_attempts_badge(self, obj):
        """Display failed attempts"""
        if obj.failed_attempts == 0:
            return format_html('<span style="color: green;">—</span>')
        
        if obj.failed_attempts >= obj.max_retries:
            return format_html(
                '<span style="color: red;"><strong>{}</strong></span>',
                obj.failed_attempts
            )
        
        return format_html(
            '<span style="color: orange;">{}</span>',
            obj.failed_attempts
        )
    failed_attempts_badge.short_description = _('Failed Attempts')
    
    actions = ['suspend_schedules', 'resume_schedules', 'send_payment_reminders']
    
    def suspend_schedules(self, request, queryset):
        """Admin action to suspend selected schedules"""
        count = queryset.filter(status='active').update(status='suspended')
        self.message_user(request, f'{count} schedules suspended.')
    suspend_schedules.short_description = _('Suspend selected schedules')
    
    def resume_schedules(self, request, queryset):
        """Admin action to resume suspended schedules"""
        count = queryset.filter(status='suspended').update(status='active')
        self.message_user(request, f'{count} schedules resumed.')
    resume_schedules.short_description = _('Resume selected schedules')
    
    def send_payment_reminders(self, request, queryset):
        """Send manual payment reminders"""
        from django.core.mail import send_mail
        from django.template.loader import render_to_string
        from django.conf import settings
        
        count = 0
        for schedule in queryset.filter(status='active'):
            user = schedule.order.user
            try:
                context = {'order': schedule.order, 'schedule': schedule}
                message = render_to_string('shop/emails/payment_reminder.html', context)
                send_mail(
                    f'Payment Reminder - Order #{schedule.order.id}',
                    message,
                    settings.DEFAULT_FROM_EMAIL,
                    [user.email],
                    html_message=message,
                    fail_silently=False,
                )
                count += 1
            except Exception as e:
                self.message_user(request, f'Error sending reminder: {e}', level='error')
        
        self.message_user(request, f'{count} reminders sent.')
    send_payment_reminders.short_description = _('Send payment reminders')
    
    def has_add_permission(self, request):
        """Schedules are created through orders"""
        return False


@admin.register(ScheduledPayment)
class ScheduledPaymentAdmin(admin.ModelAdmin):
    """Admin interface for individual scheduled payments"""
    
    list_display = (
        'payment_num', 'order_link', 'customer_link', 'amount_display',
        'status_badge', 'due_date_badge', 'retry_info'
    )
    list_filter = ('status', 'due_date', 'created_at', 'installment_schedule__order__user')
    search_fields = ('order__id', 'order__user__email', 'transaction_reference')
    
    fields = (
        'installment_schedule', 'order', 'amount', 'installment_number',
        'status', 'due_date', 'scheduled_date', 'processed_at',
        'transaction_reference', 'retry_count', 'last_retry_at',
        'error_message', 'gateway_response', 'created_at', 'updated_at'
    )
    
    readonly_fields = (
        'installment_schedule', 'order', 'created_at', 'updated_at',
        'transaction_reference', 'gateway_response'
    )
    
    def payment_num(self, obj):
        """Display payment number"""
        return f"#{obj.installment_number}/{obj.installment_schedule.total_installments}"
    payment_num.short_description = _('Payment')
    
    def order_link(self, obj):
        """Link to order"""
        url = reverse('admin:shop_order_change', args=[obj.order.id])
        return format_html('<a href="{}">#Order {}</a>', url, obj.order.id)
    order_link.short_description = _('Order')
    
    def customer_link(self, obj):
        """Link to customer"""
        user = obj.order.user
        url = reverse('admin:auth_user_change', args=[user.id])
        return format_html('<a href="{}">{}</a>', url, user.username)
    customer_link.short_description = _('Customer')
    
    def amount_display(self, obj):
        """Display amount"""
        return f"${obj.amount:.2f}"
    amount_display.short_description = _('Amount')
    
    def status_badge(self, obj):
        """Color-coded status"""
        colors = {
            'pending': 'orange',
            'processing': 'blue',
            'successful': 'green',
            'failed': 'red',
            'refunded': 'gray',
        }
        color = colors.get(obj.status, 'gray')
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            color,
            obj.get_status_display()
        )
    status_badge.short_description = _('Status')
    
    def due_date_badge(self, obj):
        """Due date with status"""
        from django.utils import timezone
        
        today = timezone.now().date()
        
        if obj.status == 'successful':
            return format_html(
                '<span style="color: green;">✓ {} (Paid)</span>',
                obj.processed_at.date() if obj.processed_at else obj.due_date
            )
        
        if obj.due_date < today:
            return format_html(
                '<span style="color: red;"><strong>OVERDUE</strong></span> '
                '({})', obj.due_date
            )
        
        return format_html('{} (in {} days)', obj.due_date, (obj.due_date - today).days)
    due_date_badge.short_description = _('Due Date')
    
    def retry_info(self, obj):
        """Display retry attempts"""
        if obj.status == 'successful':
            return '—'
        
        if obj.retry_count == 0:
            return 'Not attempted'
        
        return f'{obj.retry_count} attempt{"s" if obj.retry_count > 1 else ""}'
    retry_info.short_description = _('Retries')
    
    actions = ['mark_as_successful', 'mark_as_failed']
    
    def mark_as_successful(self, request, queryset):
        """Manually mark payments as successful"""
        count = queryset.filter(status='failed').update(status='successful')
        self.message_user(request, f'{count} payments marked successful.')
    mark_as_successful.short_description = _('Mark as successful')
    
    def mark_as_failed(self, request, queryset):
        """Manually mark payments as failed"""
        count = queryset.filter(
            status__in=['pending', 'processing']
        ).update(status='failed')
        self.message_user(request, f'{count} payments marked failed.')
    mark_as_failed.short_description = _('Mark as failed')
    
    def has_add_permission(self, request):
        """Payments are auto-created"""
        return False


# Add filter to Order Admin
class InstallmentScheduleFilter(admin.SimpleListFilter):
    """Filter orders by installment status"""
    title = _('Installment Status')
    parameter_name = 'installment'
    
    def lookups(self, request, model_admin):
        return [
            ('active', _('Active Installments')),
            ('completed', _('Completed Installments')),
            ('suspended', _('Suspended Installments')),
            ('all_installments', _('Any Installment')),
        ]
    
    def queryset(self, request, queryset):
        if self.value() == 'active':
            return queryset.filter(installment_schedule__status='active')
        if self.value() == 'completed':
            return queryset.filter(installment_schedule__status='completed')
        if self.value() == 'suspended':
            return queryset.filter(installment_schedule__status='suspended')
        if self.value() == 'all_installments':
            return queryset.filter(installment_schedule__isnull=False)
        return queryset


# Add to existing Order Admin:
# list_filter = [...existing filters..., InstallmentScheduleFilter]
