import logging
from django.contrib.auth.decorators import login_required
from django.db import models
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils import timezone
from moods.models import Mood, MoodLogData, MoodQuality, MoodReason
from scrobbles.models import Scrobble

logger = logging.getLogger(__name__)


@login_required
def checkin(request):
    """Three-step mood check-in wizard"""
    step = request.session.get("checkin_step", 1)

    if request.GET.get("back"):
        back_step = request.GET.get("back")
        if back_step == "2":
            request.session["checkin_step"] = 2
            request.session.pop("checkin_mood_id", None)
        else:
            request.session.pop("checkin_step", None)
            request.session.pop("checkin_quality", None)
            request.session.pop("checkin_mood_id", None)
        return redirect("moods:checkin")

    if request.method == "POST":
        if step == 1:
            quality = request.POST.get("mood_quality")
            if quality:
                request.session["checkin_quality"] = int(quality)
                request.session["checkin_step"] = 2
                return redirect("moods:checkin")
            qualities = [
                {"value": q.value, "name": q.name.replace("_", " ").title()}
                for q in MoodQuality
            ]
            return render(
                request, "moods/checkin_quality.html", {"qualities": qualities}
            )

        elif step == 2:
            mood_id = request.POST.get("mood")
            quality = request.session.get("checkin_quality")

            if mood_id and quality:
                request.session["checkin_mood_id"] = int(mood_id)
                request.session["checkin_step"] = 3
                return redirect("moods:checkin")

            return redirect("moods:checkin")

        elif step == 3:
            reason_id = request.POST.get("reason")
            mood_id = request.session.get("checkin_mood_id")
            quality = request.session.get("checkin_quality")

            if mood_id and quality:
                try:
                    mood = Mood.objects.get(id=mood_id)
                    log_data = MoodLogData(
                        mood_quality=quality,
                        mood_type=mood.mood_type,
                        mood_reason_ids=[int(reason_id)] if reason_id else [],
                    )

                    # Attempt to add current weather from most recent location
                    last_loc = (
                        Scrobble.objects.filter(
                            user=request.user,
                            media_type=Scrobble.MediaType.GEO_LOCATION,
                            geo_location__isnull=False,
                        )
                        .order_by("-timestamp")
                        .first()
                    )
                    if last_loc and last_loc.geo_location:
                        weather = last_loc.geo_location.current_weather
                        if weather:
                            log_data.weather_temp = weather["temp"]
                            log_data.weather_description = weather["description"]

                    scrobble = Scrobble.objects.create(
                        user=request.user,
                        mood=mood,
                        media_type=Scrobble.MediaType.MOOD,
                        timestamp=timezone.now(),
                         source="Website",
                        log=log_data.asdict,
                    )

                    # Clear session data
                    request.session.pop("checkin_step", None)
                    request.session.pop("checkin_quality", None)
                    request.session.pop("checkin_mood_id", None)

                    return redirect("moods:checkin_success")
                except Mood.DoesNotExist:
                    logger.error(f"Mood with id {mood_id} not found")

            return redirect("moods:checkin")

    if step == 1:
        qualities = [
            {"value": q.value, "name": q.name.replace("_", " ").title()}
            for q in MoodQuality
        ]
        return render(
            request, "moods/checkin_quality.html", {"qualities": qualities}
        )
    elif step == 2:
        quality = request.session.get("checkin_quality", 4)
        positive_qualities = [MoodQuality.NEUTRAL.value, MoodQuality.SLIGHTLY_PLEASANT.value,
                             MoodQuality.PLEASANT.value, MoodQuality.VERY_PLEASANT.value]
        if quality in positive_qualities:
            mood_groups = [
                ("positive", Mood.objects.filter(mood_type="positive").exclude(description__isnull=True).exclude(description="")),
                ("negative", Mood.objects.filter(mood_type="negative").exclude(description__isnull=True).exclude(description="")),
            ]
        else:
            mood_groups = [
                ("negative", Mood.objects.filter(mood_type="negative").exclude(description__isnull=True).exclude(description="")),
                ("positive", Mood.objects.filter(mood_type="positive").exclude(description__isnull=True).exclude(description="")),
            ]
        return render(request, "moods/checkin_mood.html", {"mood_groups": mood_groups})
    else:
        reasons = MoodReason.objects.all()
        return render(request, "moods/checkin_reason.html", {"reasons": reasons})


@login_required
def checkin_success(request):
    return render(request, "moods/checkin_success.html")


from scrobbles.views import ScrobbleableListView, ScrobbleableDetailView


class MoodListView(ScrobbleableListView):
    model = Mood


class MoodDetailView(ScrobbleableDetailView):
    model = Mood
