from django.db import models
from django.utils import timezone
from apps.accounts.models import User
from apps.core.models import BaseModel
from apps.business.distributor.models import DistributorID, DistributorGlobalPositionCounter

class DistributorLevelProgress(models.Model):
    distributor = models.OneToOneField(DistributorID, on_delete=models.CASCADE, related_name='level_progress')
    current_level = models.PositiveIntegerField(default=0)
    last_completed_level = models.PositiveIntegerField(default=0)
    total_positions_after = models.PositiveIntegerField(default=0)
    last_calculated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-last_calculated_at']
        indexes = [
            models.Index(fields=['distributor']),
            models.Index(fields=['current_level']),
            models.Index(fields=['last_completed_level']),
            models.Index(fields=['last_calculated_at']),
        ]

    def __str__(self):
        return f"DistributorLevelProgress(distributor={self.distributor_id}, level={self.current_level})"


class UserBonanzaCounter(BaseModel):
    class Category(models.TextChoices):
        LUCKY_DIP_BONANZA = 'LUCKY_DIP_BONANZA', 'Lucky Dip Bonanza'
        PRODUCTS_BONANZA = 'PRODUCTS_BONANZA', 'Products Bonanza'
        DOMESTIC_TRAVEL_BONANZA = 'DOMESTIC_TRAVEL_BONANZA', 'Domestic Travel Bonanza'
        INTERNATIONAL_TRAVEL_BONANZA = 'INTERNATIONAL_TRAVEL_BONANZA', 'International Travel Bonanza'
        TWO_WHEELER_BONANZA = 'TWO_WHEELER_BONANZA', 'Two Wheeler Bonanza'
        ALKALINE_WATER_DEVICE_BONANZA = 'ALKALINE_WATER_DEVICE_BONANZA', 'Alkaline Water Device Bonanza'
        GOLD_BONANZA = 'GOLD_BONANZA', 'Gold Bonanza'
        CAR_FUND_BONANZA = 'CAR_FUND_BONANZA', 'Car Fund Bonanza'

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bonanza_counters', db_index=True)
    category = models.CharField(max_length=48, choices=Category.choices, db_index=True)
    quantity = models.PositiveIntegerField(default=0)
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    notes = models.TextField(blank=True, default='')

    class Meta:
        unique_together = ('user', 'category')
        indexes = [
            models.Index(fields=['user', 'category']),
            models.Index(fields=['category', 'is_active']),
        ]

    def __str__(self):
        return f"{self.user_id} - {self.category}: qty={self.quantity}, amount={self.amount}"


class FranchiseMonthlyIncentive(BaseModel):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='franchise_monthly_incentives', db_index=True)
    period_month = models.DateField(help_text='Use first day of month as canonical value', db_index=True)
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    notes = models.TextField(blank=True, default='')

    class Meta:
        unique_together = ('user', 'period_month')
        indexes = [
            models.Index(fields=['user', 'period_month']),
            models.Index(fields=['period_month', 'is_active']),
        ]

    def __str__(self):
        return f"{self.user_id} - {self.period_month}: {self.amount}"


class RewardAchievement(BaseModel):
    """Rewards earned after level achievement - converted to supercoins"""
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reward_achievements', db_index=True)
    level = models.PositiveIntegerField(help_text='Level achieved', db_index=True)
    reward_name = models.CharField(max_length=255, help_text='e.g., "Level 5 Reward"')
    supercoin_amount = models.DecimalField(max_digits=12, decimal_places=2, help_text='Supercoins to award')
    status = models.CharField(
        max_length=20,
        choices=[
            ('earned', 'Earned'),
            ('claimed', 'Claimed'),
            ('expired', 'Expired'),
        ],
        default='earned',
        db_index=True
    )
    claimed_at = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True, default='')

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['level', 'status']),
            models.Index(fields=['created_at']),
        ]

    def __str__(self):
        return f"{self.user_id} - Level {self.level}: {self.supercoin_amount} supercoins ({self.status})"


class Service(BaseModel):
    """Available services/trips offered after level achievement"""
    
    level = models.PositiveIntegerField(db_index=True, help_text='Available from this level')
    service_name = models.CharField(max_length=255)
    service_description = models.TextField(blank=True, default='')
    category = models.CharField(
        max_length=50,
        choices=[
            ('trip', 'Trip/Travel'),
            ('service', 'Service'),
            ('experience', 'Experience'),
            ('other', 'Other'),
        ],
        default='service',
        db_index=True
    )
    quota = models.PositiveIntegerField(default=0, help_text='Max claimants for this service')
    claimed_count = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True, db_index=True)

    class Meta:
        ordering = ['level', 'service_name']
        indexes = [
            models.Index(fields=['level', 'is_active']),
            models.Index(fields=['category']),
        ]

    def __str__(self):
        return f"{self.service_name} (Level {self.level})"

    def is_quota_available(self):
        return self.claimed_count < self.quota


class ServiceClaim(BaseModel):
    """User claims a service/trip"""
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='service_claims', db_index=True)
    service = models.ForeignKey(Service, on_delete=models.CASCADE, related_name='claims', db_index=True)
    status = models.CharField(
        max_length=20,
        choices=[
            ('pending', 'Pending Approval'),
            ('approved', 'Approved'),
            ('completed', 'Completed'),
            ('rejected', 'Rejected'),
            ('cancelled', 'Cancelled'),
        ],
        default='pending',
        db_index=True
    )
    approved_by = models.ForeignKey(
        User,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='approved_service_claims'
    )
    approved_at = models.DateTimeField(null=True, blank=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True, default='')
    admin_notes = models.TextField(blank=True, default='')

    class Meta:
        ordering = ['-created_at']
        unique_together = ('user', 'service')
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['service', 'status']),
            models.Index(fields=['created_at']),
        ]

    def __str__(self):
        return f"{self.user_id} - {self.service.service_name} ({self.status})"


class Gift(BaseModel):
    """Gifts offered after level achievement"""
    
    level = models.PositiveIntegerField(db_index=True, help_text='Available from this level')
    gift_name = models.CharField(max_length=255)
    gift_description = models.TextField(blank=True, default='')
    gift_category = models.CharField(
        max_length=50,
        choices=[
            ('product', 'Product'),
            ('experience', 'Experience'),
            ('voucher', 'Voucher'),
            ('other', 'Other'),
        ],
        default='product',
        db_index=True
    )
    quota = models.PositiveIntegerField(default=0, help_text='Max claimants for this gift')
    claimed_count = models.PositiveIntegerField(default=0)
    value = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
    is_active = models.BooleanField(default=True, db_index=True)

    class Meta:
        ordering = ['level', 'gift_name']
        indexes = [
            models.Index(fields=['level', 'is_active']),
            models.Index(fields=['gift_category']),
        ]

    def __str__(self):
        return f"{self.gift_name} (Level {self.level})"

    def is_quota_available(self):
        return self.claimed_count < self.quota


class GiftClaim(BaseModel):
    """User claims a gift"""
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='gift_claims', db_index=True)
    gift = models.ForeignKey(Gift, on_delete=models.CASCADE, related_name='claims', db_index=True)
    status = models.CharField(
        max_length=20,
        choices=[
            ('pending', 'Pending Approval'),
            ('approved', 'Approved'),
            ('completed', 'Completed'),
            ('rejected', 'Rejected'),
            ('cancelled', 'Cancelled'),
        ],
        default='pending',
        db_index=True
    )
    approved_by = models.ForeignKey(
        User,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='approved_gift_claims'
    )
    approved_at = models.DateTimeField(null=True, blank=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True, default='')
    admin_notes = models.TextField(blank=True, default='')

    class Meta:
        ordering = ['-created_at']
        unique_together = ('user', 'gift')
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['gift', 'status']),
            models.Index(fields=['created_at']),
        ]

    def __str__(self):
        return f"{self.user_id} - {self.gift.gift_name} ({self.status})"