import os
import random
from django import get_version as django_version
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django import forms
from .models import Profile, Photo
from django.utils import timezone
from django.contrib.auth.models import User

class WarwickRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True, help_text="Enter your @warwick.ac.uk email address")

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if not email.endswith("@warwick.ac.uk"):
            raise forms.ValidationError("You must use a @warwick.ac.uk email address to register.")
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("This email is already in use.")
        return email

    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

class ProfileEditForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['course', 'year', 'location', 'looking_for', 'bio']
        widgets = {
            'course': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'e.g. Computer Science'}),
            'year': forms.Select(attrs={'class': 'form-select'}),
            'location': forms.Select(attrs={'class': 'form-select'}),
            'looking_for': forms.Select(attrs={'class': 'form-select'}),
            'bio': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': 'Tell others a bit about yourself...'}),
        }

def home(request):
    if request.user.is_authenticated:
        return redirect('dashboard')
    return render(request, "core/index.html")

def register(request):
    if request.method == 'POST':
        form = WarwickRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, "Welcome to Warwick Connect! Please complete your profile.")
            return redirect('profile_edit')
    else:
        form = WarwickRegistrationForm()
    return render(request, 'core/register.html', {'form': form})

@login_required
def profile_edit(request):
    profile = request.user.profile
    if request.method == 'POST':
        form = ProfileEditForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            messages.success(request, "Profile updated successfully!")
            return redirect('dashboard')
    else:
        form = ProfileEditForm(instance=profile)
    return render(request, 'core/profile_edit.html', {'form': form, 'profile': profile})

@login_required
def dashboard(request):
    all_profiles = Profile.objects.exclude(user=request.user)
    
    if not request.user.profile.is_subscribed:
        profiles_list = list(all_profiles)
        if len(profiles_list) > 12:
            visible_profiles = random.sample(profiles_list, 12)
            locked_profiles = [p for p in profiles_list if p not in visible_profiles]
        else:
            visible_profiles = profiles_list
            locked_profiles = []
    else:
        visible_profiles = all_profiles
        locked_profiles = []

    context = {
        'visible_profiles': visible_profiles,
        'locked_profiles': locked_profiles,
        'is_subscribed': request.user.profile.is_subscribed,
    }
    return render(request, 'core/dashboard.html', context)

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('dashboard')
    else:
        form = AuthenticationForm()
    return render(request, 'core/login.html', {'form': form})

def logout_view(request):
    logout(request)
    return redirect('home')
