from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Q
from django.contrib import messages
from .models import Voter, VotingRecord, Donation, VoterContact, EventParticipation
from .forms import VoterForm, VotingRecordForm, DonationForm, VoterContactForm, EventParticipationForm

def index(request):
    query = request.GET.get('q')
    if query:
        voters = Voter.objects.filter(
            Q(first_name__icontains=query) | 
            Q(last_name__icontains=query) | 
            Q(voter_id__icontains=query)
        )[:10]
    else:
        voters = Voter.objects.all().order_by('-created_at')[:5]
    
    stats = {
        'total_voters': Voter.objects.count(),
        'supporters': Voter.objects.filter(candidate_support='supporting').count(),
        'yard_signs': Voter.objects.filter(yard_sign_status='has').count(),
    }
    
    return render(request, 'core/index.html', {
        'voters': voters,
        'query': query,
        'stats': stats
    })

def voter_detail(request, pk):
    voter = get_object_or_404(Voter, pk=pk)
    
    # Forms for adding related records (initialized as empty)
    context = {
        'voter': voter,
        'voter_form': VoterForm(instance=voter),
        'voting_form': VotingRecordForm(),
        'donation_form': DonationForm(),
        'contact_form': VoterContactForm(),
        'event_form': EventParticipationForm(),
    }
    return render(request, 'core/voter_detail.html', context)

def voter_edit(request, pk):
    voter = get_object_or_404(Voter, pk=pk)
    if request.method == 'POST':
        form = VoterForm(request.POST, instance=voter)
        if form.is_valid():
            form.save()
            messages.success(request, 'Voter updated successfully.')
            return redirect('voter_detail', pk=voter.pk)
    else:
        form = VoterForm(instance=voter)
    return render(request, 'core/voter_detail.html', {'voter': voter, 'voter_form': form})

def add_voting_record(request, pk):
    voter = get_object_or_404(Voter, pk=pk)
    if request.method == 'POST':
        form = VotingRecordForm(request.POST)
        if form.is_valid():
            record = form.save(commit=False)
            record.voter = voter
            record.save()
            messages.success(request, 'Voting record added.')
    return redirect('voter_detail', pk=voter.pk)

def add_donation(request, pk):
    voter = get_object_or_404(Voter, pk=pk)
    if request.method == 'POST':
        form = DonationForm(request.POST)
        if form.is_valid():
            donation = form.save(commit=False)
            donation.voter = voter
            donation.save()
            messages.success(request, 'Donation added.')
    return redirect('voter_detail', pk=voter.pk)

def add_contact(request, pk):
    voter = get_object_or_404(Voter, pk=pk)
    if request.method == 'POST':
        form = VoterContactForm(request.POST)
        if form.is_valid():
            contact = form.save(commit=False)
            contact.voter = voter
            contact.save()
            messages.success(request, 'Contact logged.')
    return redirect('voter_detail', pk=voter.pk)

def add_event(request, pk):
    voter = get_object_or_404(Voter, pk=pk)
    if request.method == 'POST':
        form = EventParticipationForm(request.POST)
        if form.is_valid():
            participation = form.save(commit=False)
            participation.voter = voter
            participation.save()
            messages.success(request, 'Event participation added.')
    return redirect('voter_detail', pk=voter.pk)
