from django.db import models

from wagtail.models import Page
from wagtail.fields import RichTextField, StreamField
from wagtail.admin.panels import FieldPanel
from wagtail.blocks import RichTextBlock, CharBlock, StructBlock
from wagtail.images.blocks import ImageChooserBlock


class HomePage(Page):
    """Homepage."""
    hero_title = models.CharField(
        max_length=200,
        default="Ton organisation, tes règles.",
        verbose_name="Titre hero"
    )
    hero_text = models.TextField(
        default="Pas de méthode miracle, pas de système parfait. Juste des outils et des tips pour construire TON système d'organisation.",
        verbose_name="Texte hero"
    )
    hero_cta_text = models.CharField(
        max_length=50,
        default="Découvrir le blog",
        verbose_name="Texte bouton CTA"
    )

    content_panels = Page.content_panels + [
        FieldPanel('hero_title'),
        FieldPanel('hero_text'),
        FieldPanel('hero_cta_text'),
    ]

    max_count = 1  # Only one homepage

    def get_context(self, request):
        context = super().get_context(request)
        # Import here to avoid circular imports
        from apps.blog.models import BlogPage
        # Get featured articles (is_featured=True) or latest 3 if none featured
        featured = BlogPage.objects.live().filter(is_featured=True).order_by('-first_published_at')[:3]
        if not featured:
            featured = BlogPage.objects.live().order_by('-first_published_at')[:3]
        context['featured_posts'] = featured
        return context

    class Meta:
        verbose_name = "Page d'accueil"


class ContentPage(Page):
    """Generic content page (About, Contact, etc.)."""
    body = RichTextField(blank=True, verbose_name="Contenu")
    featured_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
        verbose_name="Image"
    )

    content_panels = Page.content_panels + [
        FieldPanel('featured_image'),
        FieldPanel('body'),
    ]

    class Meta:
        verbose_name = "Page de contenu"
        verbose_name_plural = "Pages de contenu"
