from django.shortcuts import render, redirect
from django.contrib import messages
from .models import Farm
from django import forms

# Simple Form class (keeping it in views for speed, or separate file is fine too. 
# best practice is forms.py but for this task I'll stick to views or create forms.py if it gets complex. 
# Let's create a forms.py to be clean).

class FarmForm(forms.ModelForm):
    class Meta:
        model = Farm
        fields = ['name', 'owner_name', 'location', 'size_hectares', 'status']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'e.g. Green Valley Farm'}),
            'owner_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'e.g. Somchai S.'}),
            'location': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Province, District'}),
            'size_hectares': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01'}),
            'status': forms.Select(attrs={'class': 'form-select'}),
        }

def dashboard(request):
    # Stats
    total_farms = Farm.objects.count()
    active_farms = Farm.objects.filter(status='active').count()
    pending_farms = Farm.objects.filter(status='pending').count()
    
    # Recent
    recent_farms = Farm.objects.order_by('-registration_date')[:5]
    
    context = {
        'total_farms': total_farms,
        'active_farms': active_farms,
        'pending_farms': pending_farms,
        'recent_farms': recent_farms,
        'page_title': 'Overview'
    }
    return render(request, 'core/index.html', context)

def farm_create(request):
    if request.method == 'POST':
        form = FarmForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Farm registered successfully!')
            return redirect('dashboard')
    else:
        form = FarmForm()
    
    return render(request, 'core/farm_form.html', {'form': form, 'page_title': 'Register New Farm'})