# Copyright (C) 2018-2025 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later

from random import shuffle

from bootstrap_datepicker_plus.widgets import DateTimePickerInput
from crispy_forms.helper import FormHelper
from django import forms
from django.forms import CheckboxSelectMultiple
from django.forms.widgets import NumberInput, TextInput
from django.utils.translation import gettext_lazy as _
from member.models import Club
from note_kfet.inputs import Autocomplete, AmountInput
from note_kfet.middlewares import get_current_request
from permission.backends import PermissionBackend
from activity.models import Activity

from .models import Food, BasicFood, TransformedFood, QRCode, Dish, Supplement, Order, Recipe


class QRCodeForms(forms.ModelForm):
    """
    Form for create QRCode for container
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['food_container'].queryset = self.fields['food_container'].queryset.filter(
            end_of_life__isnull=True,
            polymorphic_ctype__model='transformedfood',
        ).filter(PermissionBackend.filter_queryset(
            get_current_request(),
            TransformedFood,
            "view",
        ))

    class Meta:
        model = QRCode
        fields = ('food_container',)


class BasicFoodForms(forms.ModelForm):
    """
    Form for add basicfood
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({"autofocus": "autofocus"})
        self.fields['name'].required = True
        self.fields['owner'].required = True

        # Some example
        self.fields['name'].widget.attrs.update({"placeholder": _("Pasta METRO 5kg")})
        clubs = list(Club.objects.filter(PermissionBackend.filter_queryset(get_current_request(), Club, "change")).all())
        shuffle(clubs)
        self.fields['owner'].widget.attrs["placeholder"] = ", ".join(club.name for club in clubs[:4]) + ", ..."
        self.fields['order'].widget.attrs["placeholder"] = _("Specific order given to GCKs")

    class Meta:
        model = BasicFood
        fields = ('name', 'owner', 'date_type', 'expiry_date', 'allergens', 'traces', 'order',)
        widgets = {
            "owner": Autocomplete(
                model=Club,
                attrs={"api_url": "/api/members/club/"},
            ),
            "expiry_date": DateTimePickerInput(),
        }


class TransformedFoodForms(forms.ModelForm):
    """
    Form for add transformedfood
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].required = True
        self.fields['owner'].required = True

        # Some example
        self.fields['name'].widget.attrs.update({"placeholder": _("Lasagna")})
        clubs = list(Club.objects.filter(PermissionBackend.filter_queryset(get_current_request(), Club, "change")).all())
        shuffle(clubs)
        self.fields['owner'].widget.attrs["placeholder"] = ", ".join(club.name for club in clubs[:4]) + ", ..."
        self.fields['order'].widget.attrs["placeholder"] = _("Specific order given to GCKs")

    class Meta:
        model = TransformedFood
        fields = ('name', 'owner', 'order',)
        widgets = {
            "owner": Autocomplete(
                model=Club,
                attrs={"api_url": "/api/members/club/"},
            ),
        }


class BasicFoodUpdateForms(forms.ModelForm):
    """
    Form for update basicfood object
    """
    class Meta:
        model = BasicFood
        fields = ('name', 'owner', 'date_type', 'expiry_date', 'end_of_life', 'is_ready', 'order', 'allergens', 'traces')
        widgets = {
            "owner": Autocomplete(
                model=Club,
                attrs={"api_url": "/api/members/club/"},
            ),
            "expiry_date": DateTimePickerInput(),
        }


class TransformedFoodUpdateForms(forms.ModelForm):
    """
    Form for update transformedfood object
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['shelf_life'].label = _('Shelf life (in hours)')

    class Meta:
        model = TransformedFood
        fields = ('name', 'owner', 'end_of_life', 'is_ready', 'order', 'shelf_life')
        widgets = {
            "owner": Autocomplete(
                model=Club,
                attrs={"api_url": "/api/members/club/"},
            ),
            "expiry_date": DateTimePickerInput(),
            "shelf_life": NumberInput(),
        }


class AddIngredientForms(forms.ModelForm):
    """
    Form for add an ingredient
    """
    fully_used = forms.BooleanField()
    fully_used.initial = False
    fully_used.required = False
    fully_used.label = _("Fully used")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # TODO find a better way to get pk (be not url scheme dependant)
        pk = get_current_request().path.split('/')[-1]
        qs = self.fields['ingredients'].queryset.filter(
            polymorphic_ctype__model="transformedfood",
            is_ready=False,
            end_of_life='',
        ).filter(PermissionBackend.filter_queryset(get_current_request(), Food, "change"))
        if pk:
            qs = qs.exclude(pk=pk)
        self.fields['ingredients'].queryset = qs

    class Meta:
        model = TransformedFood
        fields = ('ingredients',)


class ManageIngredientsForm(forms.Form):
    """
    Form to manage ingredient
    """
    fully_used = forms.BooleanField()
    fully_used.initial = False
    fully_used.required = True
    fully_used.label = _('Fully used')

    name = forms.CharField()
    name.widget = Autocomplete(
        model=Food,
        resetable=True,
        attrs={"api_url": "/api/food/food",
               "class": "autocomplete manageingredients-autocomplete"},
    )
    name.label = _('Name')

    qrcode = forms.IntegerField()
    qrcode.widget = Autocomplete(
        model=QRCode,
        resetable=True,
        attrs={"api_url": "/api/food/qrcode/",
               "name_field": "qr_code_number",
               "class": "autocomplete"},
    )
    qrcode.label = _('QR code number')

    add_all_same_name = forms.BooleanField(
        required=False,
        label=_("Add all identical food")
    )


ManageIngredientsFormSet = forms.formset_factory(
    ManageIngredientsForm,
    extra=1,
)


class DishForm(forms.ModelForm):
    """
    Form to create a dish
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # TODO find a better way to get pk (be not url scheme dependant)
        pk = get_current_request().path.split('/')[3]
        club = Activity.objects.get(pk=pk).organizer
        qs = self.fields['main'].queryset.filter(
            owner=club,
            end_of_life=''
        ).filter(PermissionBackend.filter_queryset(get_current_request(), Food, "change"))
        self.fields['main'].queryset = qs

    class Meta:
        model = Dish
        fields = ('main', 'price', 'available')
        widgets = {
            "price": AmountInput(),
        }


class SupplementForm(forms.ModelForm):
    """
    Form to create a dish
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # TODO find a better way to get pk (be not url scheme dependant)
        pk = get_current_request().path.split('/')[3]
        club = Activity.objects.get(pk=pk).organizer
        qs = self.fields['food'].queryset.filter(
            owner=club,
            end_of_life=''
        ).filter(PermissionBackend.filter_queryset(get_current_request(), Food, "change"))
        self.fields['food'].queryset = qs

    class Meta:
        model = Supplement
        fields = '__all__'
        widgets = {
            "price": AmountInput(),
        }


# The 2 following classes are copied from treasury app
# Add a subform per supplement in the dish form, and manage correctly the link between the dish and
# its supplements. The FormSet will search automatically the ForeignKey in the Supplement model.
SupplementFormSet = forms.inlineformset_factory(
    Dish,
    Supplement,
    form=SupplementForm,
    extra=1,
)


class SupplementFormSetHelper(FormHelper):
    """
    Specify some template information for the supplement form
    """

    def __init__(self, form=None):
        super().__init__(form)
        self.form_tag = False
        self.form_method = 'POST'
        self.form_class = 'form-inline'
        self.template = 'bootstrap4/table_inline_formset.html'


class OrderForm(forms.ModelForm):
    """
    Form to order food
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # TODO find a better way to get pk (be not url scheme dependant)
        pk = get_current_request().path.split('/')[3]
        qs = self.fields['supplements'].queryset.filter(
            available=True
        ).filter(PermissionBackend.filter_queryset(get_current_request(), Supplement, "view"))
        self.fields['supplements'].queryset = qs
        qs = self.fields['dish'].queryset.filter(
            activity__pk=pk,
            available=True
        ).filter(PermissionBackend.filter_queryset(get_current_request(), Dish, "view"))
        self.fields['dish'].queryset = qs

    class Meta:
        model = Order
        exclude = ("activity", "number", "ordered_at", "served", "served_at")


class RecipeForm(forms.ModelForm):
    """
    Form to create a recipe
    """
    class Meta:
        model = Recipe
        fields = ('name', 'creater',)
        widgets = {
            "creater": Autocomplete(
                model=Club,
                attrs={"api_url": "/api/members/club/"},
            ),
        }


class RecipeIngredientsForm(forms.Form):
    """
    Form to add ingredients to a recipe
    """
    name = forms.CharField()
    name.widget = TextInput()
    name.label = _("Name")


RecipeIngredientsFormSet = forms.formset_factory(
    RecipeIngredientsForm,
    extra=1,
)


class UseRecipeForm(forms.Form):
    """
    Form to add ingredients to a TransformedFood using a Recipe
    """
    recipe = forms.ModelChoiceField(
        queryset=Recipe.objects,
        label=_('Recipe'),
    )

    ingredients = forms.ModelMultipleChoiceField(
        queryset=Food.objects,
        label=_("Ingredients"),
        widget=CheckboxSelectMultiple(),
    )
