from django.db import models
from django.utils import timezone


class NotificationCategory(models.Model):
    """Categories for different types of notifications"""
    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(blank=True)
    color_code = models.CharField(max_length=7, default="#61b239")  # Hex color code
    
    class Meta:
        verbose_name_plural = "Notification Categories"
        ordering = ['name']
    
    def __str__(self):
        return self.name


class Notification(models.Model):
    """Main notification model"""
    PRIORITY_CHOICES = [
        ('low', 'Low'),
        ('medium', 'Medium'),
        ('high', 'High'),
        ('urgent', 'Urgent'),
    ]
    
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    content = models.TextField(help_text="Full notification content")
    
    # Date and time
    published_date = models.DateTimeField(default=timezone.now)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    # Additional fields
    category = models.ForeignKey(
        NotificationCategory, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True,
        related_name='notifications'
    )
    priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='medium')
    is_active = models.BooleanField(default=True)
    is_featured = models.BooleanField(default=False, help_text="Show in featured/highlighted sections")
    
    # External links
    external_link = models.URLField(blank=True, help_text="External link for more details")
    attachment = models.FileField(upload_to='notifications/attachments/', blank=True, null=True)
    
    # SEO and metadata
    slug = models.SlugField(max_length=255, unique=True, blank=True)
    meta_description = models.TextField(max_length=160, blank=True)
    
    class Meta:
        ordering = ['-published_date', '-created_at']
        indexes = [
            models.Index(fields=['-published_date']),
            models.Index(fields=['is_active']),
            models.Index(fields=['is_featured']),
            models.Index(fields=['category']),
        ]
    
    def save(self, *args, **kwargs):
        if not self.slug:
            from django.utils.text import slugify
            base_slug = slugify(self.title)
            self.slug = base_slug
            counter = 1
            while Notification.objects.filter(slug=self.slug).exists():
                self.slug = f"{base_slug}-{counter}"
                counter += 1
        super().save(*args, **kwargs)
    
    def __str__(self):
        return self.title
    
    @property
    def formatted_date(self):
        """Returns formatted date for frontend"""
        return {
            'day': self.published_date.strftime('%d'),
            'month': self.published_date.strftime('%B'),
            'year': self.published_date.strftime('%Y'),
            'full_date': self.published_date.strftime('%Y-%m-%d'),
            'iso_date': self.published_date.isoformat(),
        }


class NotificationTag(models.Model):
    """Tags for notifications"""
    name = models.CharField(max_length=50, unique=True)
    
    class Meta:
        ordering = ['name']
    
    def __str__(self):
        return self.name


class NotificationTagRelation(models.Model):
    """Many-to-many relationship between notifications and tags"""
    notification = models.ForeignKey(Notification, on_delete=models.CASCADE, related_name='notification_tags')
    tag = models.ForeignKey(NotificationTag, on_delete=models.CASCADE, related_name='tagged_notifications')
    
    class Meta:
        unique_together = ['notification', 'tag']
    
    def __str__(self):
        return f"{self.notification.title} - {self.tag.name}"


class SiteStatistic(models.Model):
    """Statistics displayed alongside notifications"""
    name = models.CharField(max_length=100, unique=True)
    value = models.CharField(max_length=20)  # e.g., "15+", "50+", "200+", "5K+"
    description = models.TextField()
    icon = models.CharField(max_length=50, blank=True, help_text="Icon class or name")
    order = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)
    
    class Meta:
        ordering = ['order', 'name']
    
    def __str__(self):
        return f"{self.name}: {self.value}"
