import os
import platform
import json

from django import get_version as django_version
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.generic import TemplateView, FormView, CreateView
from django_pandas.io import read_frame
from django.contrib import messages

from .forms import MoodEntryForm, ContactForm, SignUpForm, DateRangeFilterForm
from .models import MoodEntry, Activity
from .mail import send_contact_message


class SignUpView(CreateView):
    form_class = SignUpForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'


class AboutView(TemplateView):
    template_name = "core/about.html"


class ContactView(FormView):
    template_name = "core/contact.html"
    form_class = ContactForm
    success_url = reverse_lazy('core:contact')

    def form_valid(self, form):
        name = form.cleaned_data['name']
        email = form.cleaned_data['email']
        message = form.cleaned_data['message']
        
        # Send email
        email_sent = send_contact_message(name, email, message)
        
        if email_sent:
            messages.success(self.request, 'Thank you for your message! We will get back to you shortly.')
        else:
            messages.error(self.request, 'Sorry, there was an error sending your message. Please try again later.')
            
        return super().form_valid(form)


class PrivacyPolicyView(TemplateView):
    template_name = "core/privacy_policy.html"


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
        activities = Activity.objects.all()
        context['activities'] = activities

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


@login_required
def dashboard(request):
    mood_entries = MoodEntry.objects.filter(user=request.user).order_by('date_time')
    form = DateRangeFilterForm(request.GET)
    if form.is_valid():
        start_date = form.cleaned_data.get('start_date')
        end_date = form.cleaned_data.get('end_date')
        if start_date:
            mood_entries = mood_entries.filter(date_time__gte=start_date)
        if end_date:
            mood_entries = mood_entries.filter(date_time__lte=end_date)

    df = read_frame(mood_entries, fieldnames=['date_time', 'mood_score'])
    if not df.empty:
        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, 'form': form})


@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})

@login_required
def save_mood_entry(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        mood_score = data.get('mood_score')
        activity_ids = data.get('activity_ids')

        mood_entry = MoodEntry.objects.create(
            user=request.user,
            mood_score=mood_score
        )

        if activity_ids:
            activities = Activity.objects.filter(id__in=activity_ids)
            mood_entry.activities.set(activities)

        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'error'}, status=400)

