from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils import timezone
from django.views import View
from django.views.generic import TemplateView
from drinks.models import Drink
from foods.models import Food
from foods.sources.openfoodfacts import search_products
from scrobbles.views import (
    ChartContextMixin,
    ScrobbleableDetailView,
    ScrobbleableListView,
)

BEVERAGE_KEYWORDS = [
    "beverage",
    "drink",
    "water",
    "beer",
    "wine",
    "juice",
    "coffee",
    "tea",
    "soda",
    "carbonated",
    "milk",
    "smoothie",
    "shake",
    "energy drink",
    "alcohol",
    "liquor",
    "spirits",
    "cocktail",
    "cider",
    "kombucha",
]


def _is_beverage(product_data: dict) -> bool:
    categories = product_data.get("categories", [])
    for cat in categories:
        cat_lower = cat.lower()
        for keyword in BEVERAGE_KEYWORDS:
            if keyword in cat_lower:
                return True
    return False


class FoodListView(ScrobbleableListView):
    model = Food


class FoodDetailView(ScrobbleableDetailView, ChartContextMixin):
    model = Food


class FoodSearchView(TemplateView):
    template_name = "foods/food_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_products(query)
            context["results"] = results
            self.request.session["food_search_results"] = results
            self.request.session["food_search_query"] = query

        return context


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

        product_index = request.POST.get("product_index")
        query = request.POST.get("query", "")
        results = request.session.get("food_search_results", [])

        try:
            product_index = int(product_index)
            product_data = results[product_index]
        except (TypeError, IndexError, ValueError):
            messages.error(request, "Invalid food selection.")
            return HttpResponseRedirect(
                reverse("foods:food_search") + f"?q={query}" if query else "/"
            )

        from scrobbles.models import Scrobble

        if _is_beverage(product_data):
            media = Drink.find_or_create_from_search(product_data)
        else:
            media = Food.find_or_create_from_search(product_data)

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

        scrobble_dict = {
            "user_id": request.user.id,
            "timestamp": timezone.now(),
            "playback_position_seconds": 0,
            "source": "Open Food Facts",
        }
        scrobble = Scrobble.create_or_update(media, 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("foods:food_list"))
