# home.blocks
import math
# Importation des blocs nécessaires de Wagtail
from wagtail.blocks import (
    CharBlock,  # Bloc de texte court
    PageChooserBlock,  # Bloc pour sélectionner une page
    RichTextBlock,  # Bloc de texte riche
    StructBlock,  # Bloc structuré composé d'autres blocs
    IntegerBlock,
    ListBlock,
    ChoiceBlock,
)

# Importation du bloc pour choisir une image
from wagtail.images.blocks import ImageChooserBlock

#
from applis.models import ApplisPage

# Importation des blocs de base
from base.blocks import BaseStreamBlock

# Définition des choix de couleur réutilisables
COLOUR_CHOICES = [
    ('primary', 'Couleur principale'),
    ('secondary', 'Couleur secondaire'),
    ('tertiary', 'Couleur tertiaire'),
    ('quaternary', 'Couleur quaternaire'),
]

class ColourChoiceBlock(ChoiceBlock):
    """
    Bloc Wagtail pour réutiliser COLOUR_CHOICES partout.
    """
    def __init__(self, **kwargs):
        super().__init__(choices=COLOUR_CHOICES, **kwargs)


class Hero01Block(StructBlock):
    title = CharBlock(required=True, help_text="Le h1 à afficher.")
    baseline = CharBlock(required=True, help_text="Le sous-titre à afficher.")

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context=parent_context)
        # Inject current_site from the request into the template context
        return context


    class Meta:
        template = "blocks/hero/hero_01_block.html"
        icon = "desktop"
        label = "Hero 01"

class SlidesBlock(StructBlock):
    title = CharBlock(required=True, help_text="Le h1 à afficher.")
    upline = CharBlock(required=True, help_text="Le sur-titre à afficher.")
    baseline = CharBlock(required=True, help_text="Le sous-titre à afficher.")
    image = ImageChooserBlock()

    class Meta:
        icon = "image"
        label = "Slides"


class Hero02Block(StructBlock):
    slideshow = ListBlock(
        SlidesBlock(),
        label = "",
        help_text = "Le h2 <UNK> afficher.",
    )

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context=parent_context)
        # Inject current_site from the request into the template context
        return context


    class Meta:
        template = "blocks/hero/hero_02_block.html"
        icon = "desktop"
        label = "Hero 02"


class FeaturedPostsBlock(StructBlock):
    """
    Features
    """
    title = CharBlock(required=True, verbose_name="Titre", help_text="Titre du post à afficher.")
    icon = CharBlock(required=True, help_text="Icône à afficher sous la forme `fa fa-check`.")
    description = RichTextBlock(required=True, help_text="Description du post à afficher.")
    featured_post = PageChooserBlock(required=True, help_text="Sélectionnez une page pour créer un lien.")
    colour = ColourChoiceBlock(required=False,label="Couleur du post",help_text="Sélectionnez la couleur du post")

    def render(self, value, context=None):
        # Rendre uniquement le contenu sans div supplémentaire
        return super().render(value, context)

    class Meta:
        icon = 'snippet'
        label = 'Page mises en avant'
        # Template complet utilisé pour générer l’aperçu (HTML page)


class ChildPagesBlock(StructBlock):
    # Le block propose à l'administrateur de choisir une page
    parent_page = PageChooserBlock(required=True, help_text="Sélectionnez la page dont vous souhaitez afficher les enfants")

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context=parent_context)
        selected_page = value.get('parent_page')
        if selected_page:
            # On récupère les 10 derniers articles en fonction de la date de publication (le plus récent en premier).
            child_pages = selected_page.get_children().live().order_by('-first_published_at')[:10]
        else:
            child_pages = []
        context['child_pages'] = child_pages
        return context

    class Meta:
        template = "blocks/child_pages_block.html"
        icon = "list-ul"
        label = "Liste des pages enfants"


class FavoriteAppsBlock(StructBlock):
    category = CharBlock(
        required=True,
        verbose_name="Catégorie",
        help_text="Nom de la catégorie (tag) à filtrer, tel qu'il apparaît dans l'admin."
    )
    limit = IntegerBlock(
        required=False,
        default=5,
        verbose_name="Limite",
        help_text="Nombre maximum d'applications à afficher (par défaut : 5)."
    )

    def get_context(self, value, parent_context=None):
        # Hérite du contexte standard (request, etc.)
        context = super().get_context(value, parent_context)
        cat_name = value.get('category')
        limit = value.get('limit') or 5

        # On récupère les applis taguées par ce nom, en s'assurant
        # qu'elles sont publiées (.live())
        apps = ApplisPage.objects.live().filter(categories_snippet__name=cat_name)[:limit]

        context['apps'] = apps
        context['category'] = cat_name
        return context

    class Meta:
        template = "blocks/favorite_apps_block.html"
        icon = "heart"
        help_text="Ne fonctionne qu'avec les pages de type applications et affiche les applications de la catégorie spécifiée"
        label = "Applications favorites"


class CTABlock(StructBlock):
    """
    L'intro
    """
    # Champ pour le texte de l'Appel à l'action (CTA) de la section héro
    intro_cta = CharBlock(
        blank=True,  # Autorise un champ vide
        verbose_name="Appel à action",  # Nom du champ dans l'interface d'administration
        max_length=255,  # Longueur maximale du texte
        help_text="Texte à afficher sur le bouton d'appel à l'action",  # Texte d'aide pour ce champ
    )

    intro_cta_link = PageChooserBlock(
        required=True,
        help_text="Choisissez une page à laquelle lier pour l'Appel à l'action",  # Texte d'aide pour ce champ
    )

    # Champ pour le texte d'introduction de la section héro
    intro_cta_text = RichTextBlock(
        blank=True,  # Autorise un champ vide
        help_text="Le texte à côté du bouton",  # Texte d'aide pour ce champ
    )

    intro_cta_colour = ColourChoiceBlock(
        required=False,
        label="Couleur du CTA",
        help_text="Sélectionnez la couleur du bouton CTA",
    )

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context=parent_context)
        return context

    class Meta:
        template = "blocks/cta_block.html"
        icon = "target"
        label = "Appel à action"
        help_text="Crée un bouton d'appel à action vers n'importe quelle page du site."


class FeaturedBlock(StructBlock):
    featured_title = CharBlock(
        label='Titre de la section'
    )
    featured_paragraph = RichTextBlock(
        label='Paragraphe de la section'
    )
    featured_posts = ListBlock(
        FeaturedPostsBlock(),
        label="Pages mise en avant",
        help_text="Liste n'importe quel type de pages du site et [à venir : ajuste automatiquement le nombre de colonne bootstrap en fonction du nombre de pages affichées.]",
    )

    def get_context(self, value, parent_context=None):
        context = super().get_context(value, parent_context)
        posts = value.get('featured_posts', [])
        count = len(posts)

        # Mapping specific counts to desired Bootstrap column sizes
        size_map = {
            1: 12,
            2: 6,
            3: 4,
            4: 3,
            5: 4,  # 3 columns per row → rows of 3 + 2
            6: 4,  # 3 columns per row → 2 rows of 3
            7: 3,  # 4 columns per row → rows of 4 + 3
            8: 3,  # 4 columns per row → 2 rows of 4
            9: 4,  # 3 columns per row → 3 rows of 3
        }
        # Fallback to ceil division for other counts
        context['col_size'] = size_map.get(count, math.ceil(12 / count) if count else 12)
        return context

    class Meta:
        template = 'blocks/featured_block.html'
        icon = 'snippet'
        label = 'Pages mises en avant'


class HomeStreamBlock(BaseStreamBlock):
    cta = CTABlock()
    favorite_apps = FavoriteAppsBlock(group="Sections")
    featured_posts = FeaturedBlock(group="Sections")
    child_pages = ChildPagesBlock(group="Sections")