from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify


class Category(models.Model):
    """Category model for organizing news"""
    name = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True, blank=True)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='categories/', blank=True, null=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    order = models.IntegerField(default=0, help_text="Display order")

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'
        ordering = ['order', 'name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)


class Tag(models.Model):
    """Tag model for news articles"""
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True, blank=True)

    class Meta:
        verbose_name = 'Tag'
        verbose_name_plural = 'Tags'
        ordering = ['name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)


class News(models.Model):
    """Main News Article model"""
    STATUS_CHOICES = [
        ('draft', 'Draft'),
        ('published', 'Published'),
        ('archived', 'Archived'),
    ]

    title = models.CharField(max_length=300)
    slug = models.SlugField(max_length=300, unique=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='news_articles')
    tags = models.ManyToManyField(Tag, blank=True, related_name='news_articles')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='news_articles')
    
    # Content
    summary = models.TextField(max_length=500, help_text="Brief summary for listing pages")
    content = models.TextField(help_text="Full article content")
    
    # Images
    featured_image = models.ImageField(upload_to='news/', help_text="Main featured image")
    thumbnail = models.ImageField(upload_to='news/thumbnails/', blank=True, null=True)
    
    # Meta
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
    is_featured = models.BooleanField(default=False, help_text="Display on homepage")
    is_breaking = models.BooleanField(default=False, help_text="Breaking news")
    views_count = models.IntegerField(default=0)
    
    # SEO
    meta_description = models.CharField(max_length=160, blank=True)
    meta_keywords = models.CharField(max_length=255, blank=True)
    
    # Timestamps
    published_at = models.DateTimeField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'News Article'
        verbose_name_plural = 'News Articles'
        ordering = ['-published_at', '-created_at']

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)


class NewsGallery(models.Model):
    """Additional images for news articles"""
    news = models.ForeignKey(News, on_delete=models.CASCADE, related_name='gallery_images')
    image = models.ImageField(upload_to='news/gallery/')
    caption = models.CharField(max_length=255, blank=True)
    order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'News Gallery Image'
        verbose_name_plural = 'News Gallery Images'
        ordering = ['order', 'created_at']

    def __str__(self):
        return f"Image for {self.news.title}"


class Comment(models.Model):
    """Comments on news articles"""
    news = models.ForeignKey(News, on_delete=models.CASCADE, related_name='comments')
    name = models.CharField(max_length=100)
    email = models.EmailField()
    content = models.TextField()
    is_approved = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Comment'
        verbose_name_plural = 'Comments'
        ordering = ['-created_at']

    def __str__(self):
        return f"Comment by {self.name} on {self.news.title}"


class Advertisement(models.Model):
    """Advertisement management"""
    POSITION_CHOICES = [
        ('header', 'Header'),
        ('sidebar', 'Sidebar'),
        ('footer', 'Footer'),
        ('between_content', 'Between Content'),
    ]

    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='ads/')
    link = models.URLField(blank=True)
    position = models.CharField(max_length=20, choices=POSITION_CHOICES)
    is_active = models.BooleanField(default=True)
    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)
    order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Advertisement'
        verbose_name_plural = 'Advertisements'
        ordering = ['position', 'order']

    def __str__(self):
        return self.title


class SiteSettings(models.Model):
    """Site-wide settings"""
    site_name = models.CharField(max_length=200, default='News Portal')
    site_logo = models.ImageField(upload_to='site/', blank=True, null=True)
    site_favicon = models.ImageField(upload_to='site/', blank=True, null=True)
    site_description = models.TextField(blank=True)
    contact_email = models.EmailField(blank=True)
    contact_phone = models.CharField(max_length=20, blank=True)
    address = models.TextField(blank=True)
    
    # Social Media
    facebook_url = models.URLField(blank=True)
    twitter_url = models.URLField(blank=True)
    instagram_url = models.URLField(blank=True)
    youtube_url = models.URLField(blank=True)
    
    # Footer
    footer_text = models.TextField(blank=True)
    copyright_text = models.CharField(max_length=200, blank=True)
    
    # About Us Page
    about_intro = models.TextField(blank=True, help_text="Brief introduction paragraph for About Us page")
    about_mission = models.TextField(blank=True, help_text="Mission statement for About Us page")
    about_vision = models.TextField(blank=True, help_text="Vision statement for About Us page")
    about_what_we_do = models.TextField(blank=True, help_text="What We Do description")
    about_what_we_do_list = models.TextField(blank=True, help_text="What We Do bullet points, one per line")
    about_team_intro = models.TextField(blank=True, help_text="Introduction for Team section")
    about_values_intro = models.TextField(blank=True, help_text="Introduction for Values section")
    about_contact_intro = models.TextField(blank=True, help_text="Introduction for Contact section on About page")
    about_banner_image = models.ImageField(upload_to='site/about/', blank=True, null=True, help_text="Banner image for About page slider")
    about_intro_image = models.ImageField(upload_to='site/about/', blank=True, null=True, help_text="Intro section image")
    about_what_we_do_image = models.ImageField(upload_to='site/about/', blank=True, null=True, help_text="What We Do section image")
    
    # Coverage areas (JSON format: [{"icon": "📺", "title": "Entertainment", "description": "..."}])
    about_coverage_json = models.TextField(blank=True, help_text="Coverage areas as JSON array: [{\"icon\": \"📺\", \"title\": \"Entertainment\", \"description\": \"...\"}]")
    
    # Core values (JSON format: [{"icon": "✓", "title": "Accuracy", "description": "..."}])
    about_values_json = models.TextField(blank=True, help_text="Core values as JSON array: [{\"icon\": \"✓\", \"title\": \"Accuracy\", \"description\": \"...\"}]")
    
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Site Settings'
        verbose_name_plural = 'Site Settings'

    def __str__(self):
        return self.site_name

    def save(self, *args, **kwargs):
        # Ensure only one instance exists
        self.pk = 1
        super().save(*args, **kwargs)

    @classmethod
    def load(cls):
        obj, created = cls.objects.get_or_create(pk=1)
        return obj

    def get_about_coverage(self):
        """Parse coverage JSON and return as list"""
        import json
        try:
            return json.loads(self.about_coverage_json)
        except (json.JSONDecodeError, TypeError):
            return [
                {"icon": "📺", "title": "Entertainment", "description": "Latest updates from movies, music, celebrities, and pop culture worldwide."},
                {"icon": "👥", "title": "Society", "description": "Stories about communities, social issues, and human interest that impact lives."},
                {"icon": "🏛️", "title": "Politics", "description": "Political news, government policies, and analysis of current affairs."},
                {"icon": "🌍", "title": "World", "description": "International news, global events, and stories from across the planet."},
                {"icon": "⚽", "title": "Sport", "description": "Sports news, match updates, player profiles, and athletic achievements."},
            ]

    def get_about_values(self):
        """Parse values JSON and return as list"""
        import json
        try:
            return json.loads(self.about_values_json)
        except (json.JSONDecodeError, TypeError):
            return [
                {"icon": "✓", "title": "Accuracy", "description": "We fact-check every story to ensure the information we provide is correct and reliable."},
                {"icon": "🛡️", "title": "Integrity", "description": "We maintain the highest ethical standards in our reporting and operations."},
                {"icon": "🔓", "title": "Independence", "description": "Our editorial decisions are made free from external influence or bias."},
                {"icon": "👁️", "title": "Transparency", "description": "We are open about our sources and methods of reporting."},
            ]

    def get_what_we_do_list(self):
        """Parse what_we_do_list from newline-separated text"""
        if self.about_what_we_do_list:
            return [line.strip() for line in self.about_what_we_do_list.strip().split('\n') if line.strip()]
        return [
            "Breaking news alerts and live updates",
            "In-depth investigative reporting",
            "Expert analysis and commentary",
            "Multimedia content including photos and videos",
            "Community-focused local stories",
            "International news perspectives",
        ]


class TeamMember(models.Model):
    """Team members for About Us page"""
    name = models.CharField(max_length=200)
    role = models.CharField(max_length=200)
    bio = models.TextField(blank=True)
    photo = models.ImageField(upload_to='site/team/', blank=True, null=True)
    order = models.IntegerField(default=0, help_text="Display order on About page")
    is_active = models.BooleanField(default=True)

    class Meta:
        verbose_name = 'Team Member'
        verbose_name_plural = 'Team Members'
        ordering = ['order', 'name']

    def __str__(self):
        return f"{self.name} - {self.role}"
