from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import User
from django.core.validators import ValidationError
from django.forms.widgets import HiddenInput
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from .models import Task, TaskList, Document


class DateInput(forms.DateInput):
    input_type = "date"


class DocumentInlineForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = [
            "title",
            "slug",
            "date",
        ]

        labels = {
            "title": _("Titel"),
            "slug": _("Permalink"),
        }


class TaskListAdminForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(
        label="Benutzer",
        help_text="Es können nur die Benutzer ausgewählt werden, die sich auf der Homepage angemeldet haben.",
        queryset=User.objects.all().order_by("username"),
        widget=FilteredSelectMultiple("User", is_stacked=False),
    )

    class Meta:
        model = TaskList
        fields = "__all__"


class TaskAdminForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = "__all__"

        labels = {
            "title": _("Titel"),
            "shortterm": _("Kürzel für den Link"),
            "slug": _("Permalink"),
            "task_list": _("Aufgabenbereich"),
            "due_date": _("Fälligkeit"),
            "completed": _("Abgeschlossen"),
            "completed_date": _("Datum der Fertigstellung"),
            "assigned_to": _("Zuweisen an"),
            "note": _("Notizen"),
            "priority": _("Priorität"),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # to get the self.fields set
        self.fields["assigned_to"].empty_label = "Alle"
        self.fields["assigned_to"].queryset = self.fields[
            "assigned_to"
        ].queryset.order_by("username")


class TaskCreateForm(forms.ModelForm):
    class Meta:
        model = Task

        fields = [
            "title",
            "task_list",
            "due_date",
            "assigned_to",
            "note",
        ]

        labels = {
            "title": _("Titel des Tasks"),
            "task_list": _("Task-Gruppe"),
            "due_date": _("Fälligkeitsdatum"),
            "assigned_to": _("Zuweisen an"),
        }

        widgets = {
            "due_date": DateInput(
                format=("%Y-%m-%d"),
            )
        }

    def __init__(self, *args, **kwargs):
        if "user" in kwargs:
            user = kwargs.pop("user")
        else:
            user = None

        super().__init__(*args, **kwargs)  # to get the self.fields set
        self.fields["assigned_to"].empty_label = "Alle"
        qs = self.fields["assigned_to"].queryset
        self.fields["assigned_to"].queryset = qs.order_by("username")

        if user:
            self.fields["task_list"].queryset = TaskList.objects.filter(users=user)

    def clean(self):
        cleaned_data = super().clean()
        assigned_to = cleaned_data["assigned_to"]

        if assigned_to:
            task_list = TaskList.objects.get(id=cleaned_data["task_list"].id)
            if not task_list.users.filter(username=assigned_to.username):
                raise ValidationError(
                    _(
                        f"User '{assigned_to}' gibt es nicht in der User-Liste der Task-Gruppe '{task_list}'."
                    )
                )

        return cleaned_data


class TaskUpdateForm(forms.ModelForm):
    class Meta:
        model = Task

        fields = [
            "assigned_to",
            "due_date",
            "priority",
            "note",
            "task_list",
        ]

        labels = {
            "due_date": _("Fälligkeitsdatum"),
            "assigned_to": _("Zuweisen an"),
        }

        widgets = {
            "due_date": DateInput(
                format=("%Y-%m-%d"),
            ),
            "task_list": HiddenInput,
        }

    def __init__(self, *args, **kwargs):
        if "task_list" in kwargs:
            task_list = kwargs.pop("task_list")
        else:
            task_list = None

        super().__init__(*args, **kwargs)  # to get the self.fields set
        self.fields["assigned_to"].empty_label = "Alle"
        if task_list:
            qs = TaskList.objects.get(id=task_list.id).users
            self.fields["assigned_to"].queryset = qs.order_by("username")


class DocumentCreateForm(forms.ModelForm):
    class Meta:
        model = Document

        fields = [
            "title",
            "date",
            "task",
        ]

        labels = {
            "title": _("Titel"),
            "date": _("Datum"),
        }

        widgets = {
            "date": DateInput(format=("%d-%m-%Y")),
            "task": HiddenInput,
        }


class InternTaskCreateForm(TaskCreateForm):
    # form for creating a task from intern page.
    class Meta:
        model = Task

        fields = [
            "title",
            "shortterm",
            "task_list",
            "due_date",
            "assigned_to",
            "note",
        ]

        labels = {
            "title": _("Titel des Tasks"),
            "shortterm": _("Kürzel für den Link"),
            "task_list": _("Task-Gruppe"),
            "due_date": _("Fälligkeitsdatum"),
            "assigned_to": _("Zuweisen an"),
        }

        widgets = {
            "due_date": DateInput(
                format=("%d-%m-%Y"),
            ),
            "task_list": HiddenInput,
        }
