from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from django.views import View
from django.views.generic import TemplateView
from drinks.fastcork import search_wines
from drinks.models import Beer, Coffee, Drink, Wine
from scrobbles.views import ScrobbleableDetailView, ScrobbleableListView


class BeerListView(ScrobbleableListView):
    model = Beer


class BeerDetailView(ScrobbleableDetailView):
    model = Beer


class WineListView(ScrobbleableListView):
    model = Wine


class WineDetailView(ScrobbleableDetailView):
    model = Wine


class CoffeeListView(ScrobbleableListView):
    model = Coffee


class CoffeeDetailView(ScrobbleableDetailView):
    model = Coffee


class DrinkListView(ScrobbleableListView):
    model = Drink


class DrinkDetailView(ScrobbleableDetailView):
    model = Drink


class QuickWaterScrobbleView(View):
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            messages.error(request, "You must be logged in to scrobble water.")
            return HttpResponseRedirect("/")

        from scrobbles.scrobblers import manual_scrobble_water

        scrobble = manual_scrobble_water(user_id=request.user.id)

        if scrobble:
            messages.success(request, "Water scrobbled!")
            return HttpResponseRedirect(scrobble.redirect_url(request.user.id))

        messages.error(request, "Failed to scrobble water.")
        return HttpResponseRedirect("/")

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)


class WineSearchView(TemplateView):
    template_name = "drinks/wine_search.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        query = self.request.GET.get("q", "").strip()
        context["query"] = query

        if query:
            results = search_wines(query)
            context["results"] = results
            self.request.session["wine_search_results"] = results
            self.request.session["wine_search_query"] = query

        return context


class WineScrobbleFromSearchView(View):
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            messages.error(request, "You must be logged in to scrobble wine.")
            return HttpResponseRedirect("/")

        wine_index = request.POST.get("wine_index")
        query = request.POST.get("query", "")
        results = request.session.get("wine_search_results", [])

        try:
            wine_index = int(wine_index)
            wine_data = results[wine_index]
        except (TypeError, IndexError, ValueError):
            messages.error(request, "Invalid wine selection.")
            return HttpResponseRedirect(
                reverse("drinks:wine_search") + f"?q={query}" if query else "/"
            )

        from scrobbles.models import Scrobble

        wine = Wine.find_or_create_from_search(wine_data)

        if not wine:
            messages.error(request, "Could not create wine from search result.")
            return HttpResponseRedirect(
                reverse("drinks:wine_search") + f"?q={query}" if query else "/"
            )

        scrobble_dict = {
            "user_id": request.user.id,
            "timestamp": timezone.now(),
            "playback_position_seconds": 0,
            "source": "FastCork",
        }
        scrobble = Scrobble.create_or_update(wine, request.user.id, scrobble_dict)

        if scrobble:
            return HttpResponseRedirect(scrobble.redirect_url(request.user.id))

        messages.error(request, "Failed to create scrobble.")
        return HttpResponseRedirect(reverse("drinks:wine_list"))
