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


ROOM_TYPE_CHOICES = [
    ("neighborhood", "Neighborhood"),
    ("topic",        "Topic"),
    ("university",   "University"),
    ("election",     "Election / Ward"),
    ("business",     "Biashara"),
    ("user",         "User Created"),
]

REACTION_CHOICES = [
    ("like",    "👍 Like"),
    ("love",    "❤️ Love"),
    ("haha",    "😂 Haha"),
    ("wow",     "😮 Wow"),
    ("sad",     "😢 Sad"),
    ("dislike", "👎 Dislike"),
]

BIASHARA_CATEGORIES = [
    ("food",        "Food & Groceries"),
    ("electronics", "Electronics & Gadgets"),
    ("clothes",     "Clothes & Fashion"),
    ("land",        "Land & Property"),
    ("services",    "Services"),
    ("furniture",   "Furniture & Home"),
    ("vehicles",    "Vehicles"),
    ("other",       "Other"),
]


class Room(models.Model):
    name        = models.CharField(max_length=100)
    slug        = models.SlugField(unique=True)
    description = models.TextField(blank=True)
    room_type   = models.CharField(max_length=20, choices=ROOM_TYPE_CHOICES, default="topic")
    icon        = models.CharField(max_length=10, blank=True, default="💬")
    neighborhood = models.CharField(max_length=50, blank=True, null=True)
    members     = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        through="RoomMembership",
        related_name="rooms",
        blank=True,
    )
    created_by  = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name="created_rooms"
    )
    created_at   = models.DateTimeField(auto_now_add=True)
    is_active    = models.BooleanField(default=True)
    is_private   = models.BooleanField(default=False)
    member_count = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ["room_type", "name"]

    def __str__(self):
        return f"{self.icon} {self.name}"

    def save(self, *args, **kwargs):
        if not self.slug:
            base = slugify(self.name)
            slug = base
            n = 1
            while Room.objects.filter(slug=slug).exclude(pk=self.pk).exists():
                slug = f"{base}-{n}"
                n += 1
            self.slug = slug
        super().save(*args, **kwargs)


class RoomMembership(models.Model):
    ROLE_CHOICES = [
        ("member",    "Member"),
        ("moderator", "Moderator"),
        ("admin",     "Admin"),
    ]
    user      = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    room      = models.ForeignKey(Room, on_delete=models.CASCADE)
    role      = models.CharField(max_length=20, choices=ROLE_CHOICES, default="member")
    joined_at = models.DateTimeField(auto_now_add=True)
    is_muted  = models.BooleanField(default=False)

    class Meta:
        unique_together = ("user", "room")

    def __str__(self):
        return f"{self.user.username} in #{self.room.slug}"


class Message(models.Model):
    """Chat messages inside a community room (for forwarding announcements)."""
    room       = models.ForeignKey(
        Room, on_delete=models.CASCADE,
        related_name="community_messages"   # ← renamed to avoid clash
    )
    user       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    content    = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    is_announcement = models.BooleanField(default=False)

    class Meta:
        ordering = ["created_at"]

    def __str__(self):
        return f"{self.user.username} → #{self.room.slug}: {self.content[:40]}"
    

class CommunityPost(models.Model):
    room       = models.ForeignKey(Room, on_delete=models.CASCADE, related_name="posts")
    author     = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="community_posts"
    )
    content    = models.TextField(blank=True)
    image      = models.ImageField(upload_to="community/posts/", blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_deleted = models.BooleanField(default=False)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.author.username} in #{self.room.slug}: {self.content[:40]}"

    def reaction_counts(self):
        counts = {}
        for choice, _ in REACTION_CHOICES:
            count = self.reactions.filter(reaction_type=choice).count()
            if count > 0:
                counts[choice] = count
        return counts


class PostReaction(models.Model):
    post          = models.ForeignKey(CommunityPost, on_delete=models.CASCADE, related_name="reactions")
    user          = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    reaction_type = models.CharField(max_length=10, choices=REACTION_CHOICES)
    created_at    = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("post", "user")


class PostComment(models.Model):
    post       = models.ForeignKey(CommunityPost, on_delete=models.CASCADE, related_name="comments")
    author     = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="community_comments"
    )
    parent     = models.ForeignKey(
        "self", on_delete=models.CASCADE,
        null=True, blank=True,
        related_name="replies"
    )
    content    = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    is_deleted = models.BooleanField(default=False)

    class Meta:
        ordering = ["created_at"]

    def __str__(self):
        return f"{self.author.username}: {self.content[:40]}"

    def reaction_counts(self):
        counts = {}
        for choice, _ in REACTION_CHOICES:
            count = self.comment_reactions.filter(reaction_type=choice).count()
            if count > 0:
                counts[choice] = count
        return counts


class CommentReaction(models.Model):
    comment       = models.ForeignKey(PostComment, on_delete=models.CASCADE, related_name="comment_reactions")
    user          = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    reaction_type = models.CharField(max_length=10, choices=REACTION_CHOICES)
    created_at    = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("comment", "user")


# ── BIASHARA MARKETPLACE ──

class BiasharaListing(models.Model):
    STATUS_CHOICES = [
        ("active",  "Active"),
        ("sold",    "Sold"),
        ("expired", "Expired"),
    ]

    seller       = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="biashara_listings"
    )
    room         = models.ForeignKey(
        Room, on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name="listings",
        help_text="Biashara room this was posted to"
    )
    title        = models.CharField(max_length=200)
    description  = models.TextField()
    price        = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
    price_label  = models.CharField(
        max_length=50, blank=True,
        help_text="e.g. 'Free', 'Negotiable', 'KES 500'"
    )
    category     = models.CharField(max_length=20, choices=BIASHARA_CATEGORIES, default="other")
    location     = models.CharField(max_length=100, blank=True, help_text="Location in Thika")
    phone        = models.CharField(max_length=20, blank=True)
    image        = models.ImageField(upload_to="biashara/", blank=True, null=True)
    image2       = models.ImageField(upload_to="biashara/", blank=True, null=True)
    image3       = models.ImageField(upload_to="biashara/", blank=True, null=True)
    status       = models.CharField(max_length=10, choices=STATUS_CHOICES, default="active")
    views_count  = models.PositiveIntegerField(default=0)
    created_at   = models.DateTimeField(auto_now_add=True)
    updated_at   = models.DateTimeField(auto_now=True)
    expires_at   = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.seller.username}: {self.title} — KES {self.price}"

    def get_price_display(self):
        if self.price_label:
            return self.price_label
        if self.price:
            return f"KES {self.price:,.0f}"
        return "Price on request"
# ── DEALS (Flash Sales) ──
class Deal(models.Model):
    CATEGORY_CHOICES = [
        ("food",        "Food & Drinks"),
        ("fashion",     "Fashion"),
        ("electronics", "Electronics"),
        ("services",    "Services"),
        ("beauty",      "Beauty & Health"),
        ("other",       "Other"),
    ]
    seller       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="deals")
    title        = models.CharField(max_length=200)
    description  = models.TextField()
    original_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    deal_price   = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    category     = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default="other")
    location     = models.CharField(max_length=200, blank=True)
    phone        = models.CharField(max_length=20, blank=True)
    image        = models.ImageField(upload_to="deals/", null=True, blank=True)
    expires_at   = models.DateTimeField()
    is_active    = models.BooleanField(default=True)
    views_count  = models.PositiveIntegerField(default=0)
    created_at   = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.title

    def is_expired(self):
        from django.utils import timezone
        return timezone.now() > self.expires_at

    def discount_percent(self):
        if self.original_price and self.deal_price and self.original_price > 0:
            return int((1 - self.deal_price / self.original_price) * 100)
        return None


# ── KAZI (Jobs) ──
class KaziJob(models.Model):
    JOB_TYPE_CHOICES = [
        ("casual",    "Casual / Daily"),
        ("part_time", "Part Time"),
        ("full_time", "Full Time"),
        ("contract",  "Contract"),
    ]
    CATEGORY_CHOICES = [
        ("domestic",    "Domestic (Househelp, Cook)"),
        ("construction","Construction & Artisan"),
        ("boda",        "Boda Boda & Transport"),
        ("tech",        "Tech & IT"),
        ("business",    "Business & Sales"),
        ("education",   "Teaching & Tutoring"),
        ("health",      "Health & Medical"),
        ("other",       "Other"),
    ]
    poster       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="kazi_jobs")
    title        = models.CharField(max_length=200)
    description  = models.TextField()
    job_type     = models.CharField(max_length=20, choices=JOB_TYPE_CHOICES, default="casual")
    category     = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default="other")
    location     = models.CharField(max_length=200, blank=True)
    neighborhood = models.CharField(max_length=100, blank=True)
    pay          = models.CharField(max_length=100, blank=True)
    phone        = models.CharField(max_length=20, blank=True)
    is_active    = models.BooleanField(default=True)
    created_at   = models.DateTimeField(auto_now_add=True)
    expires_at   = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.title


# ── EVENTS ──
class Event(models.Model):
    CATEGORY_CHOICES = [
        ("music",    "Music & Concert"),
        ("sports",   "Sports"),
        ("church",   "Church & Religious"),
        ("business", "Business & Networking"),
        ("community","Community"),
        ("education","Education"),
        ("other",    "Other"),
    ]
    organizer    = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="events")
    title        = models.CharField(max_length=200)
    description  = models.TextField()
    category     = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default="other")
    location     = models.CharField(max_length=300)
    neighborhood = models.CharField(max_length=100, blank=True)
    starts_at    = models.DateTimeField()
    ends_at      = models.DateTimeField(null=True, blank=True)
    is_free      = models.BooleanField(default=True)
    ticket_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    phone        = models.CharField(max_length=20, blank=True)
    image        = models.ImageField(upload_to="events/", null=True, blank=True)
    is_active    = models.BooleanField(default=True)
    rsvp_count   = models.PositiveIntegerField(default=0)
    created_at   = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["starts_at"]

    def __str__(self):
        return self.title


class EventRSVP(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="rsvps")
    user  = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="rsvps")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ["event", "user"]


# ── LOST & FOUND ──
class LostFound(models.Model):
    TYPE_CHOICES = [
        ("lost",  "Lost"),
        ("found", "Found"),
    ]
    CATEGORY_CHOICES = [
        ("person",     "Person"),
        ("pet",        "Pet"),
        ("item",       "Item"),
        ("vehicle",    "Vehicle"),
        ("document",   "Document / ID"),
        ("other",      "Other"),
    ]
    poster       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="lost_found_posts")
    post_type    = models.CharField(max_length=10, choices=TYPE_CHOICES)
    category     = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default="item")
    title        = models.CharField(max_length=200)
    description  = models.TextField()
    location     = models.CharField(max_length=300, blank=True)
    neighborhood = models.CharField(max_length=100, blank=True)
    phone        = models.CharField(max_length=20, blank=True)
    reward       = models.CharField(max_length=100, blank=True)
    image        = models.ImageField(upload_to="lostfound/", null=True, blank=True)
    is_resolved  = models.BooleanField(default=False)
    created_at   = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.post_type + ": " + self.title


# ── BUSINESS PROFILES ──
UNIVERSITY_CHOICES = [
    ("mku",   "Mount Kenya University"),
    ("dkut",  "Dedan Kimathi University"),
    ("kca",   "KCA University"),
    ("other", "Other"),
]

class BusinessProfile(models.Model):
    CATEGORY_CHOICES = [
        ("cyber",       "Cyber & Printing"),
        ("food",        "Food & Restaurant"),
        ("boda",        "Boda Boda Stage"),
        ("hostel",      "Hostel & Accommodation"),
        ("retail",      "Retail Shop"),
        ("services",    "Professional Services"),
        ("education",   "Education & Tutoring"),
        ("other",       "Other"),
    ]
    owner        = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="business_profile")
    shop_name    = models.CharField(max_length=200)
    slug         = models.SlugField(max_length=220, unique=True, blank=True)
    category     = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default="other")
    description  = models.TextField()
    address      = models.CharField(max_length=300)
    neighborhood = models.CharField(max_length=50, blank=True)
    near_campus  = models.CharField(max_length=20, choices=UNIVERSITY_CHOICES, blank=True)
    phone        = models.CharField(max_length=20, blank=True)
    whatsapp     = models.CharField(max_length=20, blank=True)
    email        = models.EmailField(blank=True)
    logo         = models.ImageField(upload_to="business/logos/", blank=True, null=True)
    cover_image  = models.ImageField(upload_to="business/covers/", blank=True, null=True)
    is_verified  = models.BooleanField(default=False)
    is_active    = models.BooleanField(default=True)
    followers_count = models.PositiveIntegerField(default=0)
    room         = models.OneToOneField("Room", on_delete=models.SET_NULL, null=True, blank=True, related_name="business")
    boosted_until = models.DateTimeField(null=True, blank=True)
    created_at   = models.DateTimeField(auto_now_add=True)
    updated_at   = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["-is_verified", "-created_at"]

    def __str__(self):
        return self.shop_name

    def save(self, *args, **kwargs):
        if not self.slug:
            from django.utils.text import slugify
            base = slugify(self.shop_name)
            slug = base
            n = 1
            while BusinessProfile.objects.filter(slug=slug).exclude(pk=self.pk).exists():
                slug = f"{base}-{n}"; n += 1
            self.slug = slug
        super().save(*args, **kwargs)


class BusinessService(models.Model):
    business    = models.ForeignKey(BusinessProfile, on_delete=models.CASCADE, related_name="services")
    name        = models.CharField(max_length=200)
    description = models.CharField(max_length=300, blank=True)
    price       = models.CharField(max_length=100, blank=True)
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["name"]


class BusinessPost(models.Model):
    business    = models.ForeignKey(BusinessProfile, on_delete=models.CASCADE, related_name="posts")
    title       = models.CharField(max_length=200)
    body        = models.TextField()
    image       = models.ImageField(upload_to="business/posts/", blank=True, null=True)
    is_deal     = models.BooleanField(default=False)
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]


class BusinessFollower(models.Model):
    business   = models.ForeignKey(BusinessProfile, on_delete=models.CASCADE, related_name="followers")
    user       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="followed_businesses")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ["business", "user"]


# ── CAMPUS RESOURCES ──
class CampusResource(models.Model):
    TYPE_CHOICES = [
        ("past_paper", "Past Paper"),
        ("notes",      "Lecture Notes"),
        ("tp_ip",      "TP/IP File"),
        ("module",     "Module"),
        ("other",      "Other"),
    ]
    posted_by   = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="campus_resources")
    business    = models.ForeignKey(BusinessProfile, on_delete=models.SET_NULL, null=True, blank=True, related_name="resources")
    title       = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    resource_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default="other")
    university  = models.CharField(max_length=20, choices=UNIVERSITY_CHOICES, default="mku")
    unit_code   = models.CharField(max_length=20, blank=True)
    course      = models.CharField(max_length=100, blank=True)
    year        = models.CharField(max_length=10, blank=True)
    price       = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
    is_free     = models.BooleanField(default=True)
    phone       = models.CharField(max_length=20, blank=True)
    file_url    = models.URLField(blank=True)
    image       = models.ImageField(upload_to="campus/resources/", blank=True, null=True)
    downloads   = models.PositiveIntegerField(default=0)
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]


# ── HOSTELS ──
class HostelListing(models.Model):
    TYPE_CHOICES = [
        ("bedsitter", "Bedsitter"),
        ("single",    "Single Room"),
        ("double",    "Double Room"),
        ("studio",    "Studio"),
        ("shared",    "Shared"),
    ]
    landlord     = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="hostel_listings")
    title        = models.CharField(max_length=200)
    description  = models.TextField()
    hostel_type  = models.CharField(max_length=20, choices=TYPE_CHOICES, default="bedsitter")
    near_campus  = models.CharField(max_length=20, choices=UNIVERSITY_CHOICES, default="mku")
    location     = models.CharField(max_length=300)
    distance     = models.CharField(max_length=100, blank=True)
    price        = models.DecimalField(max_digits=10, decimal_places=2)
    phone        = models.CharField(max_length=20, blank=True)
    image        = models.ImageField(upload_to="campus/hostels/", blank=True, null=True)
    is_available = models.BooleanField(default=True)
    created_at   = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]


# ── ATTACHMENTS ──
class AttachmentPost(models.Model):
    posted_by   = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="attachment_posts")
    company     = models.CharField(max_length=200)
    title       = models.CharField(max_length=200)
    description = models.TextField()
    location    = models.CharField(max_length=200, blank=True)
    course      = models.CharField(max_length=100, blank=True)
    duration    = models.CharField(max_length=100, blank=True)
    deadline    = models.DateField(null=True, blank=True)
    phone       = models.CharField(max_length=20, blank=True)
    email       = models.EmailField(blank=True)
    is_active   = models.BooleanField(default=True)
    created_at  = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
