# Create your views here.
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login

from apps.user.models import UserProfile  # Importing the UserProfile model

from .forms import LoginForm, SignUpForm  # Importing form classes for login and signup


# View function for user login
def login_view(request):
    # Check if the user is already authenticated, if so, redirect them to the home page
    if request.user.is_authenticated:
        next_page = request.GET.get('next', '/')  # Get the 'next' parameter from the URL, default to '/'
        return redirect(next_page)
    
    form = LoginForm(request.POST or None)  # Create a login form instance

    msg = None  # Initialize a message variable

    if request.method == "POST":
        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            
            # Authenticate user using the provided username and password
            user = authenticate(username=username, password=password)
            
            if user is not None:
                login(request, user)  # Log in the authenticated user
                next_page = request.GET.get('next', '/')  # Get the 'next' parameter from the URL
                return redirect(next_page)  # Redirect to the 'next' page after successful login
            else:
                msg = 'Invalid credentials'  # Set error message for invalid credentials
        else:
            msg = 'Error validating the form'  # Set error message for form validation error

    return render(request, "accounts/login.html", {"form": form, "msg": msg})


# View function for user registration
def register_user(request):
    msg = None  # Initialize a message variable
    success = False  # Initialize a success flag

    if request.method == "POST":
        form = SignUpForm(request.POST)   # Create a signup form instance
        
        if form.is_valid():
            form.save()  # Save the user details from the form
            username = form.cleaned_data.get("username")
            raw_password = form.cleaned_data.get("password1")
            
            # Authenticate the newly registered user
            user = authenticate(username=username, password=raw_password)
            
            # Create a UserProfile instance associated with the registered user
            profile = UserProfile(user=user)
            profile.save()

            msg = 'User created - please <a href="/login">login</a>.'  # Set success message with a login link
            success = True  # Set success flag to True
        else:
            msg = 'Form is not valid'  # Set error message for invalid form data
    else:
        form = SignUpForm()  # Create an empty signup form instance for GET requests

    return render(request, "accounts/register.html", {"form": form, "msg": msg, "success": success})
