from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import Profile, Tag, Startup, Investment, Message, Notification
from .forms import StartupForm, MessageForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.db.models import Sum, Q

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

class SignupForm(UserCreationForm):
    university_email = forms.EmailField(required=True, label="University or Graduate Email")
    full_name = forms.CharField(required=True)
    university_name = forms.CharField(required=True)
    graduation_year = forms.IntegerField(required=True)

    class Meta(UserCreationForm.Meta):
        fields = UserCreationForm.Meta.fields + ('university_email',)

def signup_view(request):
    if request.method == "POST":
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save()
            profile = user.profile
            profile.university = form.cleaned_data.get('university_name')
            profile.graduation_year = form.cleaned_data.get('graduation_year')
            profile.save()
            # login(request, user) # Don't login yet, show verification screen
            request.session['pending_verification_user_id'] = user.id
            return redirect('verify')
    else:
        form = SignupForm()
    return render(request, "core/signup.html", {"form": form})

def verify_view(request):
    user_id = request.session.get('pending_verification_user_id')
    if not user_id:
        return redirect('signup')
    
    if request.method == "POST":
        user = get_object_or_404(User, id=user_id)
        user.profile.is_verified = True
        user.profile.save()
        login(request, user)
        return redirect('onboarding_role')
        
    return render(request, "core/verify.html")

@login_required
def onboarding_role(request):
    if request.method == "POST":
        role = request.POST.get('role')
        request.user.profile.role = role
        request.user.profile.save()
        if role == 'INVESTOR':
            return redirect('onboarding_investor')
        else:
            return redirect('onboarding_founder')
    return render(request, "core/onboarding/role.html")

@login_required
def onboarding_investor(request):
    if request.method == "POST":
        bio = request.POST.get('bio')
        appetite = request.POST.get('appetite')
        request.user.profile.bio = bio
        request.user.profile.investment_appetite = appetite
        request.user.profile.save()
        return redirect('discover')
    return render(request, "core/onboarding/investor.html")

@login_required
def onboarding_founder(request):
    # This leads to partner matching questionnaire
    return redirect('partner_matching')

@login_required
def onboarding_partner_matching(request):
    if request.method == "POST":
        # Save questionnaire answers in JSON format
        request.user.profile.matching_answers = request.POST.dict()
        request.user.profile.save()
        return redirect('partners')
    return render(request, "core/onboarding/partner_matching.html")

@login_required
def discover_startups(request):
    startups = Startup.objects.filter(status='FUNDING').order_by('-created_at')
    return render(request, "core/discover.html", {"startups": startups})

@login_required
def find_partners(request):
    current_profile = request.user.profile
    # Basic partner matching logic:
    # 1. Same university
    # 2. Shared interests (Tags) - if we had tags set up properly
    # For now, let's just prioritize same university and then others.
    
    partners = Profile.objects.filter(role='FOUNDER').exclude(user=request.user)
    
    # Sort by same university
    partners = sorted(partners, key=lambda p: p.university == current_profile.university, reverse=True)
    
    return render(request, "core/partners.html", {"partners": partners})

@login_required
def my_portfolio(request):
    profile = request.user.profile
    investments = Investment.objects.filter(investor=profile)
    total_invested = investments.aggregate(Sum('amount'))['amount__sum'] or 0
    my_startups = Startup.objects.filter(founder=profile)
    return render(request, "core/portfolio.html", {
        "investments": investments,
        "total_invested": total_invested,
        "my_startups": my_startups
    })

@login_required
def startup_detail(request, pk):
    startup = get_object_or_404(Startup, pk=pk)
    return render(request, "core/startup_detail.html", {"startup": startup})

@login_required
def invest(request, pk):
    startup = get_object_or_404(Startup, pk=pk)
    if request.method == "POST":
        amount = request.POST.get('amount')
        Investment.objects.create(
            investor=request.user.profile,
            startup=startup,
            amount=amount
        )
        startup.raised_amount += float(amount)
        startup.save()
        return redirect('portfolio')
    return render(request, "core/invest.html", {"startup": startup})

@login_required
def post_startup(request):
    if request.method == "POST":
        form = StartupForm(request.POST)
        if form.is_valid():
            startup = form.save(commit=False)
            startup.founder = request.user.profile
            startup.save()
            return redirect('portfolio')
    else:
        form = StartupForm()
    return render(request, "core/create_startup.html", {"form": form})

@login_required
def messages_view(request):
    profile = request.user.profile
    # Get all unique profiles the current user has chatted with
    sent_to = Message.objects.filter(sender=profile).values_list('receiver', flat=True)
    received_from = Message.objects.filter(receiver=profile).values_list('sender', flat=True)
    
    chat_partner_ids = set(list(sent_to) + list(received_from))
    chat_partners = Profile.objects.filter(id__in=chat_partner_ids)
    
    return render(request, "core/messages.html", {"chat_partners": chat_partners})

@login_required
def chat_detail(request, pk):
    sender_profile = request.user.profile
    receiver_profile = get_object_or_404(Profile, pk=pk)
    
    messages = Message.objects.filter(
        (Q(sender=sender_profile) & Q(receiver=receiver_profile)) |
        (Q(sender=receiver_profile) & Q(receiver=sender_profile))
    ).order_by('timestamp')
    
    # Mark messages as read
    Message.objects.filter(sender=receiver_profile, receiver=sender_profile, is_read=False).update(is_read=True)
    
    if request.method == "POST":
        form = MessageForm(request.POST)
        if form.is_valid():
            message = form.save(commit=False)
            message.sender = sender_profile
            message.receiver = receiver_profile
            message.save()
            return redirect('chat_detail', pk=pk)
    else:
        form = MessageForm()
    
    return render(request, "core/chat_detail.html", {
        "chat_partner": receiver_profile,
        "messages": messages,
        "form": form
    })
