"""
Views for signals app.
"""
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.views.decorators.http import require_POST
from .models import Coin, TradingSignal, SignalStatus
from .forms import CoinForm, TradingSignalForm
from .services import accept_available_daily_signals


def coin_list_view(request):
    """
    View to display list of all cryptocurrencies.
    """
    coins = Coin.objects.filter(is_active=True)
    
    # Simple pagination
    paginator = Paginator(coins, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'signals/coin_list.html', {'page_obj': page_obj, 'coins': coins})


def signal_list_view(request):
    """
    View to display all trading signals.
    """
    signals = TradingSignal.objects.all()
    
    # Filter by status
    status = request.GET.get('status')
    if status:
        signals = signals.filter(status=status)
    
    # Filter by signal type
    signal_type = request.GET.get('type')
    if signal_type:
        signals = signals.filter(signal_type=signal_type)
    
    # Order by created date
    signals = signals.order_by('-created_at')
    
    # Pagination
    paginator = Paginator(signals, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'signals/signal_list.html', {
        'page_obj': page_obj,
        'signals': signals,
    })


def signal_detail_view(request, signal_id):
    """
    View to display details of a specific trading signal.
    """
    signal = get_object_or_404(TradingSignal, id=signal_id)
    return render(request, 'signals/signal_detail.html', {'signal': signal})


@login_required
def my_signals_view(request):
    """
    View to display user's signals (for admin to see their created signals).
    """
    signals = TradingSignal.objects.filter(created_by=request.user).order_by('-created_at')
    
    paginator = Paginator(signals, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'signals/my_signals.html', {'page_obj': page_obj})


@login_required
@require_POST
def accept_daily_signal_view(request):
    """
    Accept today's available automated signal(s) and credit profit.
    """
    result = accept_available_daily_signals(request.user)

    if result['accepted_count']:
        messages.success(
            request,
            f"Signal accepted successfully. ${result['total_profit']:.2f} profit has been added to your wallet.",
        )
    else:
        messages.error(request, 'No active automated signal is available right now.')

    return redirect('dashboard')


# Admin views for managing signals
@login_required
def admin_signal_create(request):
    """
    Admin view to create a new trading signal.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    if request.method == 'POST':
        form = TradingSignalForm(request.POST)
        if form.is_valid():
            signal = form.save(commit=False)
            signal.created_by = request.user
            signal.save()
            messages.success(request, 'Trading signal created successfully!')
            return redirect('admin_signals')
    else:
        form = TradingSignalForm()
    
    return render(request, 'signals/admin_signal_form.html', {'form': form, 'action': 'Create'})


@login_required
def admin_signal_edit(request, signal_id):
    """
    Admin view to edit an existing trading signal.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    signal = get_object_or_404(TradingSignal, id=signal_id)
    
    if request.method == 'POST':
        form = TradingSignalForm(request.POST, instance=signal)
        if form.is_valid():
            form.save()
            messages.success(request, 'Trading signal updated successfully!')
            return redirect('admin_signals')
    else:
        form = TradingSignalForm(instance=signal)
    
    return render(request, 'signals/admin_signal_form.html', {'form': form, 'action': 'Edit'})


@login_required
def admin_signals_view(request):
    """
    Admin view to manage all trading signals.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    signals = TradingSignal.objects.all().order_by('-created_at')
    
    # Filter options
    status = request.GET.get('status')
    if status:
        signals = signals.filter(status=status)
    
    signal_type = request.GET.get('type')
    if signal_type:
        signals = signals.filter(signal_type=signal_type)
    
    paginator = Paginator(signals, 15)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    return render(request, 'signals/admin_signals.html', {'page_obj': page_obj})


@login_required
def admin_coins_view(request):
    """
    Admin view to manage coins.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    coins = Coin.objects.all().order_by('name')
    return render(request, 'signals/admin_coins.html', {'coins': coins})


@login_required
def admin_coin_create(request):
    """
    Admin view to create a new coin.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    if request.method == 'POST':
        form = CoinForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, 'Coin created successfully!')
            return redirect('admin_coins')
    else:
        form = CoinForm()
    
    return render(request, 'signals/admin_coin_form.html', {'form': form, 'action': 'Create'})


@login_required
def admin_coin_edit(request, coin_id):
    """
    Admin view to edit a coin.
    """
    if not request.user.is_staff:
        messages.error(request, 'You do not have permission to access this page.')
        return redirect('dashboard')
    
    coin = get_object_or_404(Coin, id=coin_id)
    
    if request.method == 'POST':
        form = CoinForm(request.POST, request.FILES, instance=coin)
        if form.is_valid():
            form.save()
            messages.success(request, 'Coin updated successfully!')
            return redirect('admin_coins')
    else:
        form = CoinForm(instance=coin)
    
    return render(request, 'signals/admin_coin_form.html', {'form': form, 'action': 'Edit'})
