"""
Django admin configuration for signals app.
"""
from decimal import Decimal

from django.contrib import admin
from django.http import HttpResponseRedirect
from django.urls import path, reverse
from django.utils.html import format_html

from .models import AutomatedUserSignal, Coin, SignalProgramSettings, TradingSignal, UserSignalPlan
from .services import dispatch_manual_signals_for_plans


@admin.register(Coin)
class CoinAdmin(admin.ModelAdmin):
    """
    Admin configuration for Coin model.
    """
    list_display = ('name', 'symbol', 'current_price', 'is_active', 'is_featured', 'created_at')
    list_filter = ('is_active', 'is_featured')
    search_fields = ('name', 'symbol')
    list_editable = ('is_active', 'is_featured')


@admin.register(TradingSignal)
class TradingSignalAdmin(admin.ModelAdmin):
    """
    Admin configuration for TradingSignal model.
    """
    list_display = ('coin', 'signal_type', 'entry_price', 'target_price', 'stop_loss', 'status', 'created_by', 'created_at')
    list_filter = ('signal_type', 'status', 'coin')
    search_fields = ('coin__name', 'description')
    list_editable = ('status',)
    readonly_fields = ('created_at', 'updated_at', 'created_by')
    
    def save_model(self, request, obj, form, change):
        if not obj.created_by:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(SignalProgramSettings)
class SignalProgramSettingsAdmin(admin.ModelAdmin):
    """
    Admin configuration for automated signal program settings.
    """
    fieldsets = (
        ('Automation', {
            'fields': (
                'is_enabled',
                'target_multiplier',
                'completion_days',
                'daily_signal_time',
                'signal_expiry_minutes',
                'default_coin',
                'default_signal_type',
            ),
        }),
        ('Test Mode', {
            'fields': (
                'test_mode_enabled',
                'test_interval_minutes',
            ),
        }),
        ('Dashboard Market Section', {
            'fields': (
                'show_dashboard_market_overview',
                'dashboard_market_title',
            ),
        }),
        ('Telegram CTA', {
            'fields': (
                'telegram_channel_enabled',
                'telegram_channel_title',
                'telegram_channel_description',
                'telegram_button_text',
                'telegram_channel_url',
                'telegram_contact_username',
            ),
        }),
    )
    list_display = (
        'settings_name',
        'is_enabled',
        'show_dashboard_market_overview',
        'telegram_channel_enabled',
        'daily_signal_time',
        'test_mode_enabled',
        'updated_at',
    )
    list_editable = (
        'is_enabled',
        'show_dashboard_market_overview',
        'telegram_channel_enabled',
        'daily_signal_time',
        'test_mode_enabled',
    )

    def settings_name(self, obj):
        return 'Automated Signal Program'
    settings_name.short_description = 'Program'

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


@admin.register(UserSignalPlan)
class UserSignalPlanAdmin(admin.ModelAdmin):
    """
    Admin configuration for user signal plans.
    """
    list_display = (
        'user',
        'deposit',
        'principal_amount',
        'target_amount',
        'credited_profit_amount',
        'accepted_days',
        'completion_days',
        'status',
        'started_at',
    )
    list_filter = ('status',)
    search_fields = ('user__username', 'deposit__id')
    actions = ('send_signal_now',)
    readonly_fields = (
        'user',
        'deposit',
        'principal_amount',
        'target_multiplier',
        'target_amount',
        'target_profit_amount',
        'credited_profit_amount',
        'daily_profit_amount',
        'completion_days',
        'accepted_days',
        'started_at',
        'completed_at',
        'cancelled_at',
        'created_at',
        'updated_at',
    )

    def current_wallet_balance(self, obj):
        wallet = getattr(obj.user, 'wallet', None)
        return wallet.balance if wallet else '0.00'
    current_wallet_balance.short_description = 'Wallet Balance'

    def get_list_display(self, request):
        return (
            'user',
            'deposit',
            'current_wallet_balance',
            'principal_amount',
            'target_amount',
            'credited_profit_amount',
            'accepted_days',
            'completion_days',
            'status',
            'started_at',
            'send_now_button',
        )

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path(
                '<int:plan_id>/send-now/',
                self.admin_site.admin_view(self.send_now_view),
                name='signals_usersignalplan_send_now',
            ),
        ]
        return custom_urls + urls

    def send_now_button(self, obj):
        wallet = getattr(obj.user, 'wallet', None)
        wallet_balance = wallet.balance if wallet else Decimal('0.00')

        if obj.status != 'ACTIVE':
            return format_html('<span style="color:#94a3b8;">Unavailable</span>')
        if wallet_balance <= Decimal('0.00'):
            return format_html('<span style="color:#f59e0b;">No Balance</span>')
        if not obj.user.is_active_signal:
            return format_html('<span style="color:#ef4444;">Paused</span>')

        url = reverse('admin:signals_usersignalplan_send_now', args=[obj.pk])
        return format_html(
            '<a href="{}" class="btn btn-sm btn-primary" style="padding:6px 14px; white-space:nowrap;">Send Now</a>',
            url,
        )
    send_now_button.short_description = 'Manual Send'

    @admin.action(description='Send signal now for selected plans')
    def send_signal_now(self, request, queryset):
        result = dispatch_manual_signals_for_plans(queryset)
        self.message_user(
            request,
            f"{result['success_count']} signal(s) sent manually. {result['skipped_count']} skipped.",
        )

    def send_now_view(self, request, plan_id):
        result = dispatch_manual_signals_for_plans(UserSignalPlan.objects.filter(pk=plan_id))
        self.message_user(
            request,
            f"{result['success_count']} signal(s) sent manually. {result['skipped_count']} skipped.",
        )
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('admin:signals_usersignalplan_changelist')))

    def has_add_permission(self, request):
        return False


@admin.register(AutomatedUserSignal)
class AutomatedUserSignalAdmin(admin.ModelAdmin):
    """
    Admin configuration for automated user signals.
    """
    list_display = (
        'user',
        'plan',
        'signal_date',
        'signal_type',
        'profit_amount',
        'status',
        'scheduled_for',
        'expires_at',
        'accepted_at',
    )
    list_filter = ('status', 'signal_type', 'signal_date')
    search_fields = ('user__username', 'plan__deposit__id', 'coin__name')
    readonly_fields = (
        'user',
        'plan',
        'coin',
        'signal_type',
        'signal_date',
        'day_number',
        'scheduled_for',
        'expires_at',
        'accepted_at',
        'profit_amount',
        'entry_price',
        'target_price',
        'stop_loss',
        'transaction',
        'created_at',
        'updated_at',
    )
