from django import forms
from django.utils.translation import gettext_lazy as _

from G_Affectation.models import MentionPointDeVente
from G_Affectation.services import points_des_mentions
from facturation.models import Configuration, PointDeVente

from .access import peut_gerer_tous_les_taux, points_taux_accessibles
from .models import ConfigurationTaux


def mentions_accessibles(user):
    if not peut_gerer_tous_les_taux(user):
        return MentionPointDeVente.objects.none()
    accessible_ids = set(
        points_taux_accessibles(user).values_list("pk", flat=True)
    )
    eligible = [
        mention_id for mention_id, members in points_des_mentions().items()
        if members and members <= accessible_ids
    ]
    return MentionPointDeVente.objects.filter(pk__in=eligible).order_by("nom", "pk")


class ConfigurationTauxForm(forms.Form):
    mode = forms.ChoiceField(
        label=_("Mode d'application"), choices=ConfigurationTaux.MODE_CHOICES,
        widget=forms.RadioSelect,
    )
    taux_global = forms.DecimalField(
        label=_("Taux global CDF pour 1 USD"),
        max_digits=18, decimal_places=2, min_value=0.01, required=False,
        widget=forms.NumberInput(attrs={"class": "form-control", "step": "0.01", "min": "0.01"}),
    )

    def __init__(self, *args, instance=None, **kwargs):
        initial = kwargs.setdefault("initial", {})
        if instance:
            initial.setdefault("mode", instance.mode)
            initial.setdefault("taux_global", instance.taux_global)
        else:
            legacy = Configuration.objects.first()
            initial.setdefault("mode", ConfigurationTaux.MODE_GLOBAL)
            initial.setdefault("taux_global", getattr(legacy, "taux_change", 1) or 1)
        super().__init__(*args, **kwargs)
        self.instance = instance

    def clean(self):
        cleaned = super().clean()
        mode = cleaned.get("mode")
        taux_global = cleaned.get("taux_global")
        if mode == ConfigurationTaux.MODE_GLOBAL and taux_global is None:
            self.add_error("taux_global", _("Saisissez le taux général."))
        elif mode == ConfigurationTaux.MODE_PAR_CIBLE:
            # Le champ est masque et desactive dans ce mode. On conserve sa
            # derniere valeur uniquement pour un futur retour au mode general ;
            # elle n'est jamais utilisee pour calculer un prix par cible.
            if self.instance is not None:
                cleaned["taux_global"] = self.instance.taux_global
            else:
                legacy = Configuration.objects.first()
                cleaned["taux_global"] = getattr(legacy, "taux_change", 1) or 1
        return cleaned


class RegleTauxForm(forms.Form):
    TYPE_POINT = "point"
    TYPE_MENTION = "mention"
    type_cible = forms.ChoiceField(
        label=_("Type de cible"),
        choices=((TYPE_POINT, _("Un point de vente")), (TYPE_MENTION, _("Une mention"))),
        widget=forms.RadioSelect,
    )
    point_de_vente = forms.ModelChoiceField(
        label=_("Point de vente"), queryset=PointDeVente.objects.none(), required=False,
        empty_label=_("Choisir un point de vente"),
        widget=forms.Select(attrs={"class": "form-select"}),
    )
    mention = forms.ModelChoiceField(
        label=_("Mention"), queryset=MentionPointDeVente.objects.none(), required=False,
        empty_label=_("Choisir une mention"),
        widget=forms.Select(attrs={"class": "form-select"}),
    )
    taux = forms.DecimalField(
        label=_("Taux CDF pour 1 USD"), max_digits=18, decimal_places=2,
        min_value=0.01,
        widget=forms.NumberInput(attrs={"class": "form-control", "step": "0.01", "min": "0.01"}),
    )
    actif = forms.BooleanField(label=_("Règle active"), required=False, initial=True)

    def __init__(self, *args, user=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["point_de_vente"].queryset = points_taux_accessibles(user)
        self.fields["mention"].queryset = mentions_accessibles(user)
        if not peut_gerer_tous_les_taux(user):
            self.fields["type_cible"].choices = ((self.TYPE_POINT, _("Un point de vente")),)

    def clean(self):
        cleaned = super().clean()
        if cleaned.get("type_cible") == self.TYPE_POINT:
            if not cleaned.get("point_de_vente"):
                self.add_error("point_de_vente", _("Choisissez un point de vente."))
            cleaned["mention"] = None
        elif cleaned.get("type_cible") == self.TYPE_MENTION:
            if not cleaned.get("mention"):
                self.add_error("mention", _("Choisissez une mention."))
            cleaned["point_de_vente"] = None
        return cleaned
