import os
import platform

from django import get_version as django_version
from django.shortcuts import render, redirect
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from .forms import MoodEntryForm
from .models import MoodEntry
from django_pandas.io import read_frame


def home(request):
    """Render the home page with mood entries."""
    context = {
        'project_name': "PixelMinds",
    }
    if request.user.is_authenticated:
        mood_entries = MoodEntry.objects.filter(user=request.user).order_by('-date_time')[:7]
        context['mood_entries'] = mood_entries

    return render(request, "core/index.html", context)


@login_required
def dashboard(request):
    mood_entries = MoodEntry.objects.filter(user=request.user).order_by('date_time')
    df = read_frame(mood_entries, fieldnames=['date_time', 'mood_score'])
    df['date_time'] = df['date_time'].dt.strftime('%Y-%m-%d')
    chart_data = df.to_json(orient='records')
    return render(request, 'core/dashboard.html', {'chart_data': chart_data})


@login_required
def create_mood_entry(request):
    if request.method == 'POST':
        form = MoodEntryForm(request.POST)
        if form.is_valid():
            mood_entry = form.save(commit=False)
            mood_entry.user = request.user
            
            # Assign color based on mood score
            mood_score = form.cleaned_data['mood_score']
            if mood_score == 1:
                mood_entry.color_code = '#FF0000'  # Red
            elif mood_score == 2:
                mood_entry.color_code = '#FFC107'  # Amber
            elif mood_score == 3:
                mood_entry.color_code = '#FFFF00'  # Yellow
            elif mood_score == 4:
                mood_entry.color_code = '#4CAF50'  # Green
            elif mood_score == 5:
                mood_entry.color_code = '#2196F3'  # Blue
            
            mood_entry.save()
            form.save_m2m()  # Save the many-to-many relationships
            return redirect('core:index')
    else:
        form = MoodEntryForm()
    
    return render(request, 'core/mood_entry_form.html', {'form': form})
