import secrets

from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.shortcuts import redirect, render

from .models import ApiToken, UserProfile


def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            UserProfile.objects.get_or_create(user=user)
            login(request, user)
            messages.success(request, 'Registration successful.')
            return redirect('landing:home')
    else:
        form = UserCreationForm()
    return render(request, 'profiles/register.html', {'form': form})


def user_login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('landing:home')
    else:
        form = AuthenticationForm(request)
    return render(request, 'profiles/login.html', {'form': form})


def user_logout(request):
    if request.method == 'POST':
        logout(request)
        return redirect('landing:home')
    return redirect('landing:home')


@login_required
def settings_page(request):
    tokens = request.user.api_tokens.all()
    context = {'tokens': tokens}
    return render(request, 'profiles/settings.html', context)


@login_required
def token_create(request):
    if request.method == 'POST':
        label = request.POST.get('label', '').strip() or 'API token'
        token = secrets.token_urlsafe(48)
        ApiToken.objects.create(
            user=request.user,
            token=token,
            key_prefix=token[:8],
            label=label,
        )
        messages.success(request, 'Token created.')
    return redirect('profiles:settings')


@login_required
def token_delete(request, token_id):
    ApiToken.objects.filter(id=token_id, user=request.user).delete()
    return redirect('profiles:settings')