import logging

import pendulum
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from scrobbles.models import Scrobble
from scrobbles.views import ScrobbleableDetailView, ScrobbleableListView
from tasks.models import Task

from vrobbler.apps.tasks.todoist import get_todoist_access_token

logger = logging.getLogger(__name__)


class TaskListView(ScrobbleableListView):
    model = Task


class TaskDetailView(ScrobbleableDetailView):
    model = Task

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        if self.object.title != "Weigh-in":
            return ctx

        scrobbles = list(
            Scrobble.objects.filter(
                user=self.request.user,
                task=self.object,
                log__weight__isnull=False,
            ).order_by("timestamp")
        )
        if not scrobbles:
            return ctx

        labels = []
        weight_data = []
        body_fat_data = []
        bmi_data = []
        for s in scrobbles:
            ts = s.timestamp
            if isinstance(ts, str):
                ts = pendulum.parse(ts)
            labels.append(ts.strftime("%Y-%m-%d"))
            log = s.log if isinstance(s.log, dict) else {}
            raw_weight = log.get("weight")
            weight_data.append(
                float(raw_weight) if raw_weight is not None else None
            )
            raw_bf = log.get("body_fat")
            body_fat_data.append(
                float(raw_bf) if raw_bf is not None else None
            )
            raw_bmi = log.get("bmi")
            bmi_data.append(
                float(raw_bmi) if raw_bmi is not None else None
            )

        ctx["weighin_chart"] = {
            "labels": labels,
            "datasets": [
                {
                    "label": "Weight",
                    "data": weight_data,
                    "borderColor": "#4bc0c0",
                    "fill": False,
                    "yAxisID": "y",
                },
                {
                    "label": "Body Fat %",
                    "data": body_fat_data,
                    "borderColor": "#ff6384",
                    "fill": False,
                    "yAxisID": "y1",
                },
                {
                    "label": "BMI",
                    "data": bmi_data,
                    "borderColor": "#36a2eb",
                    "fill": False,
                    "yAxisID": "y2",
                },
            ],
        }
        return ctx


@api_view(["GET"])
@permission_classes([IsAuthenticated])
def todoist_oauth(request):
    logger.info(
        "[todoist_oauth] called",
        extra={"user_id": request.user.id, "get_data": request.GET},
    )

    get_todoist_access_token(
        request.user.id, request.GET.get("state"), request.GET.get("code")
    )

    logger.info(
        "[todoist_oauth] finished",
        extra={"user_id": request.user.id},
    )
    messages.add_message(
        request,
        messages.SUCCESS,
        f"Todoist successfully configured",
    )

    success_url = reverse_lazy("vrobbler-home")
    return HttpResponseRedirect(success_url)
