from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.models import User
from courses.models import Course
from .forms import UserRegistrationForm, UserLoginForm, UserUpdateForm, ProfileUpdateForm, CompleteProfileForm
from django.contrib.auth.decorators import login_required

def register(request):
    # Si l'utilisateur est deja connecté, on le redirige vers la page de profil
    if request.user.is_authenticated:
        return redirect('profile')
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password1']
            )
            auth_login(request, user)
            return redirect('profile')
    else:
        form = UserRegistrationForm()
    return render(request, 'users/register.html', {'form': form})

def login(request):
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                auth_login(request, user)
                return redirect('profile')
    else:
        form = UserLoginForm()
    return render(request, 'users/login.html', {'form': form})

def logout(request):
    auth_logout(request)
    return redirect('login')

@login_required(login_url='login')
def profile(request):
    if not hasattr(request.user, 'profile'):
        return redirect('complete_profile')
    return render(request, 'users/profile.html')

@login_required(login_url='login')
def complete_profile(request):
    if hasattr(request.user, 'profile'):
        return redirect('profile')  # Redirige si le profil existe déjà

    if request.method == 'POST':
        form = CompleteProfileForm(request.POST)
        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.save()
            messages.success(request, 'Votre profil a été créé avec succès !')
            return redirect('profile')
    else:
        form = CompleteProfileForm()

    return render(request, 'users/complete_profile.html', {'form': form})

@login_required(login_url='login')
def profile_update(request):
    if request.method == 'POST':
        user_form = UserUpdateForm(request.POST, instance=request.user)
        profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
        if profile_form.is_valid():
            profile_form.save()
            messages.success(request, 'Votre profil a été mis à jour avec succès !')
            return redirect('profile')
    else:
        user_form = UserUpdateForm(instance=request.user)
        profile_form = ProfileUpdateForm(instance=request.user.profile)
    return render(request, 'users/profile_update.html', {'user_form': user_form, 'profile_form': profile_form})

@login_required(login_url='login')
def account_update(request):
    if request.method == 'POST':
        user_form = UserUpdateForm(request.POST, instance=request.user)
        if user_form.is_valid():
            user_form.save()
            # On affiche un message flash pour confirmer la modification
            messages.success(request, 'Les paramètre de votre compte ont été mis à jour avec succès !')
            return redirect('profile')
    else:
        user_form = UserUpdateForm(instance=request.user)
    return render(request, 'users/account_update.html', {'user_form': user_form})

@login_required(login_url='login')
def my_courses(request):
    user_courses = Course.objects.filter(author=request.user.id)
    print(user_courses)
    return render(request, 'users/my_courses.html', {'user_courses' : user_courses})

def create_post(request):
    # Implement post creation logic here
    return render(request, 'users/create_post.html')

def another_profile(request, user_id):
    user = User.objects.get(id=user_id)
    return render(request, 'users/another_profile.html', {'user': user})
