from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from ckeditor_uploader.fields import RichTextUploadingField


class LandingPage(models.Model):
    title = models.CharField(max_length=200, help_text='Internal name')
    slug = models.SlugField(max_length=120, unique=True,
                            help_text='URL slug — page will live at /p/<slug>/')

    # Hero
    headline = models.CharField(max_length=255)
    subheadline = models.CharField(max_length=500, blank=True)
    hero_image = models.ImageField(upload_to='landing/', blank=True, null=True)
    cta_text = models.CharField(max_length=80, default='Get In Touch')
    cta_phone = models.CharField(max_length=30, blank=True,
                                 help_text='Optional click-to-call number')

    # Body — full rich-text content
    body_html = RichTextUploadingField(blank=True)

    # Linked properties shown on the page
    properties = models.ManyToManyField('properties.Property', blank=True,
                                        related_name='landing_pages')

    # Toggles
    show_inquiry_form = models.BooleanField(default=True)
    show_chatbot = models.BooleanField(default=True)
    is_published = models.BooleanField(default=True)

    # Estate card display
    location_short = models.CharField(max_length=120, blank=True,
                                      help_text="Short location label, e.g. 'Ketti, FCT Abuja'")
    starting_price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True,
                                         help_text='Lowest price to display on cards, in Naira')

    # Theming
    theme_color = models.CharField(max_length=20, default='#1a8754',
                                   help_text='Hex color for accents, e.g. #1a8754')

    # SEO
    meta_title = models.CharField(max_length=200, blank=True)
    meta_description = models.CharField(max_length=300, blank=True)

    # Stats
    views_count = models.PositiveIntegerField(default=0)

    created_by = models.ForeignKey('auth.User', on_delete=models.SET_NULL,
                                   blank=True, null=True, related_name='landing_pages')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)[:120]
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('landing_pages:detail', kwargs={'slug': self.slug})
