import datetime

from django import forms
from django.contrib.auth import get_user_model
from django.forms.utils import to_current_timezone
from django.utils import timezone

from la_chariotte.order.models import GroupedOrder, Item


class GroupedOrderForm(forms.ModelForm):
    deadline_date = forms.DateField(
        label="Date limite de commande",
        widget=forms.DateInput(attrs={"type": "date"}, format=("%Y-%m-%d")),
    )
    deadline_time = forms.TimeField(
        label="Heure limite de commande",
        widget=forms.TimeInput(attrs={"type": "time"}),
        initial=datetime.time(hour=23, minute=59, second=59),
    )
    is_phone_mandatory = forms.BooleanField(
        label="Numéro de téléphone obligatoire pour les participants",
        required=False,
    )

    class Meta:
        model = GroupedOrder
        fields = [
            "name",
            "deadline_date",
            "deadline_time",
            "delivery_date",
            "delivery_slot",
            "place",
            "description",
            "is_phone_mandatory",
        ]
        widgets = {
            "name": forms.TextInput(
                attrs={"placeholder": "ex : Des oranges pour Noël"}
            ),
            "delivery_date": forms.DateInput(
                attrs={"type": "date"},
                format=("%Y-%m-%d"),
            ),
            "delivery_slot": forms.TextInput(
                attrs={"placeholder": "14h - 17h (facultatif)"}
            ),
            "place": forms.TextInput(attrs={"placeholder": "(facultatif)"}),
            "description": forms.Textarea(
                attrs={
                    "placeholder": "Plus d'infos sur la commande groupée ? (facultatif)"
                }
            ),
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user")
        super().__init__(*args, **kwargs)

        # When updating an existing order, reuse existing values
        if kwargs["instance"]:
            self.instance.deadline = to_current_timezone(self.instance.deadline)
            self.initial["deadline_date"] = self.instance.deadline.date()
            self.initial["deadline_time"] = self.instance.deadline.time()

    def save(self, commit=True):
        self.instance.orga = get_user_model().objects.get(id=self.user.pk)
        return super().save(commit=commit)

    def clean(self):
        cleaned_data = self.cleaned_data
        self.instance.deadline = timezone.make_aware(
            datetime.datetime.combine(
                self.cleaned_data["deadline_date"],
                self.cleaned_data["deadline_time"],
            )
        )
        return cleaned_data


class ItemCreateForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ["name", "price", "max_limit"]

    def __init__(self, *args, **kwargs):
        self.grouped_order = kwargs.pop("grouped_order")
        super().__init__(*args, **kwargs)

    def save(self, commit=True):
        self.instance.grouped_order = GroupedOrder.objects.get(id=self.grouped_order.pk)
        return super().save(commit=commit)


class JoinGroupedOrderForm(forms.Form):
    code = forms.CharField(label="Code pour rejoindre la commande", max_length=6)

    def clean_code(self):
        form_code = self.cleaned_data["code"]
        if not GroupedOrder.objects.filter(code=form_code).exists():
            raise forms.ValidationError(
                "Désolé, nous ne trouvons aucune commande avec ce code"
            )
        return form_code
