import uuid
from django.db import models
from django.conf import settings
from django.utils.text import slugify
from accounts.models import VendorProfile


class Product(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    """Product model for vendor listings"""

    CATEGORY_CHOICES = (
        ('fashion', 'Fashion & Accessories'),
        ('beauty', 'Beauty & Personal Care'),
        ('electronics', 'Electronics & Gadgets'),
        ('food', 'Food & Drinks'),
        ('home', 'Home & Garden'),
        ('sports', 'Sports & Outdoors'),
        ('books', 'Books & Education'),
        ('vehicles', 'Vehicles'),
        ('phones', 'Phones & Tablets'),
        ('computers', 'Computers'),
        ('health', 'Health'),
        ('services', 'Services'),
        ('gifts', 'Gifts & Custom Items'),
        ('other', 'Other'),
    )

    CONDITION_CHOICES = (
        ('new', 'Brand New'),
        ('like_new', 'Like New'),
        ('good', 'Good'),
        ('fair', 'Fair'),
        ('used', 'Used'),
    )

    STATUS_CHOICES = (
        ('active', 'Active'),
        ('sold', 'Sold'),
        ('paused', 'Paused'),
        ('deleted', 'Deleted'),
        ('coming_soon', 'Coming Soon'),
    )

    # Vendor relationship
    vendor = models.ForeignKey(
        VendorProfile,
        on_delete=models.CASCADE,
        related_name='products'
    )

    # SEO-friendly slug
    slug = models.SlugField(max_length=300, unique=True, blank=True)

    # Basic fields (available to all vendors)
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES)
    condition = models.CharField(max_length=20, choices=CONDITION_CHOICES)
    description = models.TextField(max_length=300)
    is_available = models.BooleanField(default=True)
    is_negotiable = models.BooleanField(default=False)
    tags = models.CharField(max_length=200, blank=True, null=True, help_text="Comma-separated tags")

    # Primary image (required for all vendors)
    primary_image = models.ImageField(upload_to='products/')

    # Upgraded vendor fields
    old_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True, help_text="Original price for discount display")
    video = models.FileField(upload_to='product_videos/', blank=True, null=True)
    is_featured = models.BooleanField(default=False)

    # Product attributes
    brand = models.CharField(max_length=100, blank=True, null=True)
    size = models.CharField(max_length=50, blank=True, null=True)
    color = models.CharField(max_length=50, blank=True, null=True)
    weight = models.CharField(max_length=50, blank=True, null=True)

    # Inventory
    stock_quantity = models.PositiveIntegerField(default=1)

    # Delivery
    delivery_available = models.BooleanField(default=False)
    delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    delivery_time = models.CharField(max_length=100, blank=True, null=True)

    # Location
    pickup_location = models.CharField(max_length=200, blank=True, null=True)

    # Status and metrics
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active')
    views = models.IntegerField(default=0)

    # Coming soon
    available_from = models.DateTimeField(null=True, blank=True)

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

    class Meta:
        db_table = 'products'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} - KES {self.price}"

    def save(self, *args, **kwargs):
        if not self.slug:
            base_slug = f"{slugify(self.name)}-{slugify(self.vendor.shop_name)}"
            slug = base_slug
            counter = 1
            while Product.objects.filter(slug=slug).exclude(pk=self.pk).exists():
                slug = f"{base_slug}-{counter}"
                counter += 1
            self.slug = slug
        super().save(*args, **kwargs)

    @property
    def discount_percentage(self):
        """Calculate discount percentage if old_price is set"""
        if self.old_price and self.old_price > self.price:
            return int(((self.old_price - self.price) / self.old_price) * 100)
        return 0

    @property
    def tags_list(self):
        """Return tags as a list"""
        if self.tags:
            return [tag.strip() for tag in self.tags.split(',')]
        return []


class ProductImage(models.Model):
    """Additional images for products (upgraded vendors only)"""
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='additional_images'
    )
    image = models.ImageField(upload_to='products/')
    order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'product_images'
        ordering = ['order']

    def __str__(self):
        return f"Image for {self.product.name}"


class Wishlist(models.Model):
    """Wishlist for buyers to save products"""
    buyer = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='wishlists'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='wishlisted_by'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'wishlists'
        unique_together = ('buyer', 'product')
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.buyer.full_name} - {self.product.name}"


class Review(models.Model):
    """Product reviews by buyers"""
    buyer = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='reviews'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='reviews'
    )
    rating = models.IntegerField(choices=[(i, i) for i in range(1, 6)])
    comment = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'reviews'
        unique_together = ('buyer', 'product')
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.buyer.full_name} - {self.product.name} ({self.rating})"


class ProductLike(models.Model):
    """Likes for products - social engagement"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='product_likes'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='likes'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'product_likes'
        unique_together = ('user', 'product')
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.full_name} likes {self.product.name}"


class ProductDislike(models.Model):
    """Dislikes for products - social engagement"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='product_dislikes'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='dislikes'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'product_dislikes'
        unique_together = ('user', 'product')
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.full_name} dislikes {self.product.name}"


class ProductComment(models.Model):
    """Comments on products with threading support"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='product_comments'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='replies'
    )
    content = models.TextField(max_length=1000)
    is_deleted = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'product_comments'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.full_name} on {self.product.name}: {self.content[:50]}"

    @property
    def reply_count(self):
        return self.replies.filter(is_deleted=False).count()


class RecentlyViewed(models.Model):
    """Track recently viewed products for buyers"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='recently_viewed'
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        related_name='viewed_by'
    )
    viewed_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'recently_viewed'
        unique_together = ('user', 'product')
        ordering = ['-viewed_at']

    def __str__(self):
        return f"{self.user.full_name} viewed {self.product.name}"
