from django.shortcuts import render, redirect
from django.utils import timezone
from .models import Consumption
from .forms import ConsumptionForm, SignUpForm
from datetime import timedelta
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm

# A simple mapping for caffeine content. This can be made more complex later.
CAFFEINE_MAP = {
    'coffee': {'small': 95, 'medium': 140, 'large': 210},
    'tea': {'small': 26, 'medium': 40, 'large': 55},
    'energy': {'small': 80, 'medium': 120, 'large': 160},
    'decaf': {'small': 2, 'medium': 4, 'large': 7},
}

def index(request):
    if not request.session.session_key:
        request.session.create()
    session_key = request.session.session_key

    if request.method == 'POST':
        form = ConsumptionForm(request.POST)
        if form.is_valid():
            consumption = form.save(commit=False)
            if request.user.is_authenticated:
                consumption.user = request.user
            else:
                consumption.session_key = session_key
            consumption.save()
            return redirect('index')
    else:
        form = ConsumptionForm()

    # Get today's consumption
    today = timezone.now().date()
    start_of_day = timezone.make_aware(timezone.datetime.combine(today, timezone.datetime.min.time()))
    end_of_day = start_of_day + timedelta(days=1)

    if request.user.is_authenticated:
        consumptions_today = Consumption.objects.filter(
            user=request.user,
            timestamp__gte=start_of_day,
            timestamp__lt=end_of_day
        ).order_by('-timestamp')
    else:
        consumptions_today = Consumption.objects.filter(
            session_key=session_key,
            timestamp__gte=start_of_day,
            timestamp__lt=end_of_day
        ).order_by('-timestamp')

    total_caffeine = sum(
        CAFFEINE_MAP.get(c.drink_type, {}).get(c.size, 0) for c in consumptions_today
    )
    total_drinks = consumptions_today.count()

    context = {
        'form': form,
        'consumptions_today': consumptions_today,
        'total_caffeine': total_caffeine,
        'total_drinks': total_drinks,
    }
    return render(request, 'core/index.html', context)

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

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('index')
    else:
        form = AuthenticationForm()
    return render(request, 'registration/login.html', {'form': form})

def logout_view(request):
    logout(request)
    return redirect('index')

@login_required
def profile(request):
    consumptions = Consumption.objects.filter(user=request.user).order_by('-timestamp')
    
    # Calculate statistics
    total_drinks = consumptions.count()
    total_caffeine = sum(CAFFEINE_MAP.get(c.drink_type, {}).get(c.size, 0) for c in consumptions)
    
    context = {
        'consumptions': consumptions,
        'total_drinks': total_drinks,
        'total_caffeine': total_caffeine,
    }
    return render(request, 'core/profile.html', context)
