from django.db import models
from django.utils.text import slugify
from django_ckeditor_5.fields import CKEditor5Field
from apps.accounts.models import User
from apps.accounts.fields import WebPImageField


class PortfolioCategory(models.Model):
    tenant = models.ForeignKey(
        'tenants.Tenant', on_delete=models.CASCADE,
        null=True, blank=True, related_name='portfolio_categories'
    )
    name  = models.CharField(max_length=100)
    slug  = models.SlugField(max_length=120)
    order = models.PositiveIntegerField(default=1)

    class Meta:
        ordering = ['order']
        unique_together = [('tenant', 'slug')]
        verbose_name = 'Portfolio Category'
        verbose_name_plural = 'Portfolio Categories'

    def __str__(self):
        return self.name


class PortfolioItem(models.Model):
    tenant          = models.ForeignKey(
        'tenants.Tenant', on_delete=models.CASCADE,
        null=True, blank=True, related_name='portfolio_items'
    )
    title           = models.CharField(max_length=200)
    slug            = models.SlugField(max_length=250, blank=True)
    category_label  = models.CharField(max_length=150, help_text='Displayed tag e.g. "Design, Development & Digital Marketing"')
    category        = models.ForeignKey(PortfolioCategory, on_delete=models.SET_NULL, null=True, blank=True)
    short_description = models.TextField(help_text='Shown on portfolio card')
    full_description  = CKEditor5Field(config_name='extended', blank=True)
    thumbnail       = WebPImageField(upload_to='portfolio/')
    image_alt       = models.CharField(max_length=200, blank=True, help_text='Alt text for the thumbnail (SEO + accessibility)')
    client_url      = models.URLField(blank=True)
    technologies    = models.CharField(max_length=200, blank=True, help_text='Comma-separated list')
    date_completed  = models.DateField(null=True, blank=True)

    # ── Case Study ────────────────────────────────────────────────────────────
    client_problem  = models.TextField(blank=True,
                          help_text='What problem did the client have?')
    our_solution    = models.TextField(blank=True,
                          help_text='How did we solve it?')
    project_outcome = models.TextField(blank=True,
                          help_text='Results, launch details, impact')

    # ── Visibility ────────────────────────────────────────────────────────────
    show_on_home = models.BooleanField(default=False, help_text='Show in homepage portfolio row')
    home_order   = models.PositiveIntegerField(default=99, help_text='Order on homepage (lower = first)')
    is_active    = models.BooleanField(default=True)
    is_featured  = models.BooleanField(default=False)

    # ── Meta ──────────────────────────────────────────────────────────────────
    added_by    = models.ForeignKey(User, on_delete=models.SET_NULL,
                      null=True, blank=True, related_name='portfolio_items')
    view_count  = models.PositiveIntegerField(default=0, editable=False)
    case_score  = models.PositiveSmallIntegerField(default=0, editable=False,
                      help_text='Auto-computed case study completeness 0-100')

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-date_completed', '-created_at']
        unique_together = [('tenant', 'slug')]
        verbose_name = 'Portfolio Item'
        verbose_name_plural = 'Portfolio Items'

    def __str__(self):
        return self.title

    def compute_case_score(self):
        """0-100 case study completeness score (10 checks, matching edit-panel JS)."""
        score = 0
        if self.title:                              score += 1
        if self.thumbnail:                          score += 1
        if self.category_id:                        score += 1
        if len(self.short_description or '') > 10:  score += 1
        if len(self.client_problem or '') > 20:     score += 1
        if len(self.our_solution or '') > 20:       score += 1
        if len(self.project_outcome or '') > 20:    score += 1
        if len(self.full_description or '') > 50:   score += 1
        if self.client_url:                         score += 1
        if self.technologies:                       score += 1
        return round(score / 10 * 100)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        update_fields = kwargs.get('update_fields')
        if update_fields is None or 'case_score' in update_fields:
            self.case_score = self.compute_case_score()
        super().save(*args, **kwargs)


class PortfolioImage(models.Model):
    """
    One picture in a brand's showcase, up to ten per brand.

    Kept as rows rather than a repeating set of columns on PortfolioItem, so a
    brand can carry one image or ten without the table changing shape, and so
    removing one is a delete rather than a shuffle of numbered fields.

    order is filled from the upload sequence. There is no order box on the
    form, matching every other listing in this panel.
    """
    item      = models.ForeignKey('PortfolioItem', on_delete=models.CASCADE,
                                  related_name='gallery')
    image     = WebPImageField(upload_to='portfolio/gallery/')
    alt       = models.CharField(max_length=200, blank=True, default='')
    order     = models.PositiveIntegerField(default=1)
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ['order', 'id']
        verbose_name = 'Portfolio Image'

    def __str__(self):
        return f'{self.item.title} image {self.order}'
