from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse
from .models import Farmer, AgriculturalHolding, Region, Constituency
from .forms import FarmerForm, HoldingForm
import csv

def dashboard(request):
    """Public National Dashboard Overview with Analytics"""
    total_farmers = Farmer.objects.count()
    total_holdings = AgriculturalHolding.objects.count()
    regions = Region.objects.all()
    
    # Simple stats per region
    region_stats = []
    for region in regions:
        farmers_in_region = Farmer.objects.filter(constituency__region=region).count()
        region_stats.append({'name': region.name, 'count': farmers_in_region})
    
    # Stats by primary activity
    activity_stats = []
    for code, label in AgriculturalHolding.HOLDING_TYPES:
        count = AgriculturalHolding.objects.filter(primary_activity=code).count()
        activity_stats.append({'label': label, 'value': count})

    context = {
        "project_name": "NAIMS - Namibia",
        "total_farmers": total_farmers,
        "total_holdings": total_holdings,
        "region_stats": sorted(region_stats, key=lambda x: x['count'], reverse=True),
        "activity_stats": activity_stats,
        "all_regions": regions,
    }
    return render(request, "core/index.html", context)

@login_required
def farmer_list(request):
    """View list of registered farmers with simple filtering."""
    region_id = request.GET.get('region')
    farmers = Farmer.objects.all().select_related('constituency__region')
    
    if region_id:
        farmers = farmers.filter(constituency__region_id=region_id)
        
    regions = Region.objects.all()
    return render(request, "core/farmer_list.html", {
        "farmers": farmers,
        "regions": regions,
        "selected_region": int(region_id) if region_id else None
    })

@login_required
def farmer_register(request):
    """Register a new farmer and their first holding."""
    if request.method == "POST":
        f_form = FarmerForm(request.POST)
        h_form = HoldingForm(request.POST)
        
        if f_form.is_valid() and h_form.is_valid():
            farmer = f_form.save()
            holding = h_form.save(commit=False)
            holding.farmer = farmer
            holding.save()
            
            messages.success(request, f"Farmer {farmer.name} registered successfully!")
            return redirect('farmer_list')
    else:
        f_form = FarmerForm()
        h_form = HoldingForm()
        
    return render(request, "core/farmer_form.html", {
        "f_form": f_form,
        "h_form": h_form
    })

@login_required
def farmer_detail(request, pk):
    """View details of a single farmer."""
    farmer = get_object_or_404(Farmer.objects.select_related('constituency__region'), pk=pk)
    return render(request, "core/farmer_detail.html", {"farmer": farmer})

def export_report(request):
    """Public export of agricultural holdings report."""
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="naims_agricultural_holdings_report.csv"'
    
    writer = csv.writer(response)
    writer.writerow(['Farmer Name', 'Region', 'Constituency', 'Primary Activity', 'Size (Hectares)'])
    
    holdings = AgriculturalHolding.objects.select_related('farmer__constituency__region').all()
    for h in holdings:
        writer.writerow([
            h.farmer.name,
            h.farmer.constituency.region.name,
            h.farmer.constituency.name,
            h.get_primary_activity_display(),
            h.size_hectares
        ])
        
    return response