from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from .models import Project, MindMapNode, MindMapConnection
from .ai_helpers import generate_initial_mindmap

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('project_list')
    else:
        form = UserCreationForm()
    return render(request, 'registration/signup.html', {'form': form})

def home(request):
    return render(request, 'core/index.html')

@login_required
def project_list(request):
    projects = Project.objects.filter(user=request.user).order_by('-created_at')
    return render(request, 'core/project_list.html', {'projects': projects})

@login_required
def project_detail(request, pk):
    project = get_object_or_404(Project, pk=pk, user=request.user)
    nodes = project.nodes.all()
    connections = project.connections.all()
    return render(request, 'core/project_detail.html', {
        'project': project,
        'nodes': nodes,
        'connections': connections
    })

@login_required
def create_project(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        industry = request.POST.get('industry')
        goal = request.POST.get('goal')
        project = Project.objects.create(user=request.user, title=title, industry=industry, goal=goal)
        # Automatically generate the first mind map based on the input
        generate_initial_mindmap(project)
        return redirect('project_detail', pk=project.pk)
    return render(request, 'core/create_project.html')

@login_required
def regenerate_mindmap(request, pk):
    project = get_object_or_404(Project, pk=pk, user=request.user)
    if request.method == 'POST':
        project.nodes.all().delete()
        project.connections.all().delete()
        generate_initial_mindmap(project)
    return redirect('project_detail', pk=project.pk)