from django.db import models
from django.core.validators import RegexValidator

def shop_logo_path(instance, filename):
    return f"shop_logos/{instance.name}/{filename}"

class Theme(models.Model):
    THEME_CHOICES = [
        ('light', 'Light Mode'),
        ('dark', 'Dark Mode'),
    ]

    tenant = models.OneToOneField('tenants.Tenant', on_delete=models.CASCADE, null=True, blank=True)
    mode = models.CharField(
        max_length=10,
        choices=THEME_CHOICES,
        default='light',
        help_text="Choose between light and dark mode"
    )

    # Fixed professional blue color for consistent branding
    primary_color = models.CharField(
        max_length=7,
        default='#2563eb',  # Professional blue instead of green
        validators=[RegexValidator(
            regex=r'^#(?:[0-9a-fA-F]{3}){1,2}$',
            message="Enter a valid HEX color code.",
        )],
        help_text="Professional blue brand color",
        editable=False  # Make it non-editable in admin
    )

    def __str__(self):
        return f"{self.get_mode_display()} Theme"

    class Meta:
        verbose_name = "Theme"
        verbose_name_plural = "Themes"

    def get_secondary_color(self):
        """Generate a darker shade of the primary color for secondary elements"""
        # Simple darkening by reducing RGB values
        hex_color = self.primary_color.lstrip('#')
        rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
        darker_rgb = tuple(max(0, int(c * 0.8)) for c in rgb)
        return f"#{darker_rgb[0]:02x}{darker_rgb[1]:02x}{darker_rgb[2]:02x}"

class Shop(models.Model):
    # Tenant relationship
    tenant = models.ForeignKey('tenants.Tenant', on_delete=models.CASCADE, related_name='shops', null=True, blank=True)

    # Shop details
    name = models.CharField(max_length=255)
    address = models.TextField()
    phone = models.CharField(
        max_length=15,
        validators=[RegexValidator(r'^\+?\d{9,15}$', "Enter a valid phone number.")]
    )
    email = models.EmailField()
    website = models.URLField(blank=True, null=True)
    logo = models.ImageField(upload_to=shop_logo_path, blank=True, null=True)

    # Mpesa API settings (C2B)
    mpesa_consumer_key = models.CharField(max_length=255, blank=True, null=True)
    mpesa_consumer_secret = models.CharField(max_length=255, blank=True, null=True)
    mpesa_short_code = models.CharField(max_length=10, blank=True, null=True)
    mpesa_passkey = models.CharField(max_length=255, blank=True, null=True)
    mpesa_env = models.CharField(
        max_length=10,
        choices=[('sandbox', 'Sandbox'), ('production', 'Production')],
        default='sandbox'
    )

    # SMTP Email settings
    smtp_host = models.CharField(max_length=255, blank=True, null=True)
    smtp_port = models.PositiveIntegerField(blank=True, null=True)
    smtp_user = models.EmailField(blank=True, null=True)
    smtp_password = models.CharField(max_length=255, blank=True, null=True)
    smtp_use_tls = models.BooleanField(default=True)
    smtp_use_ssl = models.BooleanField(default=False)

    # SMS API settings
    sms_api_url = models.URLField(blank=True, null=True)
    sms_api_key = models.CharField(max_length=255, blank=True, null=True)
    sms_sender_id = models.CharField(max_length=50, blank=True, null=True)

    def __str__(self):
        return self.name

    def get_logo_url(self):
        if self.logo:
            return self.logo.url
        return "/static/images/default_logo.png"

    class Meta:
        verbose_name = "Shop"
        verbose_name_plural = "Shops"