from __future__ import annotations

import django_filters as filters
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field

from .models import Post, PostCategory


class PostFilter(filters.FilterSet):
    title = filters.CharFilter(field_name="title", lookup_expr="icontains", label="Title")
    category = filters.ModelChoiceFilter(
        field_name="category",
        queryset=PostCategory.objects.all(),
        label="Category",
    )
    status = filters.ChoiceFilter(field_name="status", choices=Post.STATUS_CHOICES, label="Status")
    published_at = filters.DateTimeFromToRangeFilter(
        field_name="published_at",
        label="Published between",
        widget=filters.widgets.RangeWidget(
            attrs={
                "type": "datetime-local",
                "style": "color-scheme: light;",
                "class": "border border-gray-300 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",
            }
        ),
    )

    class Meta:
        model = Post
        fields = ["title", "category", "status", "published_at"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        helper = FormHelper()
        helper.form_tag = False
        helper.layout = Layout(
            Field("title"),
            Field("category"),
            Field("status"),
            Field("published_at"),
        )
        self.form.helper = helper

