from django.db import models
from django.utils.translation import gettext_lazy as _
from decimal import Decimal, InvalidOperation

class Service(models.Model):
    title = models.CharField(max_length=200)
    icon_class = models.CharField(max_length=100, help_text=_("مثال: bi bi-activity"))
    image = models.ImageField(upload_to='contact_images/', blank=True, null=True)
    description = models.TextField()
    order = models.PositiveIntegerField(default=0, help_text=_("ترتيب العرض في الصفحة الرئيسية"))
    slug = models.SlugField(unique=True)

    class Meta:
        ordering = ['order'] 

    def __str__(self):
        return self.title


class ServiceDetail(models.Model):
    service = models.OneToOneField(Service, on_delete=models.CASCADE)
    subtitle = models.CharField(max_length=255, blank=True, null=True)
    content = models.TextField(blank=True, null=True)
    image_main = models.ImageField(upload_to="services/", blank=True, null=True)
    image_secondary = models.ImageField(upload_to="services/", blank=True, null=True)
    experience_label = models.CharField(max_length=100, default=_("سنوات"), blank=True, null=True)
    experience_text = models.CharField(max_length=200, default=_("من الخبرة في المجال"), blank=True, null=True)
    experience_years = models.PositiveIntegerField(default=0, blank=True, null=True)
    cta_title = models.CharField(max_length=200, blank=True, null=True)
    cta_text = models.TextField(blank=True, null=True)
    cta_icon_class = models.CharField(max_length=100, default="bi bi-rocket-takeoff-fill", blank=True)
    cta_button_text = models.CharField(max_length=100, default=_("تواصل معنا الآن"), blank=True)
    cta_button_link = models.URLField(default="/contact", blank=True)
    show_pricing_switch = models.BooleanField(default=True, help_text="اظهار مفتاح الشهرى/سنوياً")

    def __str__(self):
        return f"{_('تفاصيل')} {self.service.title}"


class ServiceDetailFeature(models.Model):
    service_detail = models.ForeignKey(ServiceDetail, on_delete=models.CASCADE, related_name='features')
    title = models.CharField(max_length=255)
    icon_class = models.CharField(max_length=100, default="bi bi-check-circle-fill",
                                  help_text=_("مثال: bi bi-check-circle-fill"))

    def __str__(self):
        return self.title


class PricingPlan(models.Model):
    service = models.ForeignKey("Service", on_delete=models.CASCADE, related_name='pricing_plans', null=True)

    PLAN_TYPES = [
        ("basic", _("الأساسية")),
        ("business", _("الأعمال")),
        ("enterprise", _("المؤسسات")),
        ("plus", _("بلَس")),
    ]

    title = models.CharField(max_length=100)
    plan_type = models.CharField(max_length=20, choices=PLAN_TYPES)

    price_monthly = models.DecimalField(max_digits=10, decimal_places=2)
    price_yearly = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)

    description = models.TextField()
    features = models.TextField(help_text=_("أدخل كل ميزة في سطر"))
    is_popular = models.BooleanField(default=False)

    discount_percentage = models.PositiveIntegerField(
        default=0,
        help_text=_("قيمة الخصم بالنسبة المئوية (مثال: 20 تعني خصم 20%)"),
        blank=True,
        null=True
    )

    def __str__(self):
        return self.title

    def get_plan_type_translated(self):
        translations = {
            "basic": _("الأساسية"),
            "business": _("الأعمال"),
            "enterprise": _("المؤسسات"),
            "plus": _("بلَس"),
        }
        return translations.get(self.plan_type, self.plan_type)

    def get_discounted_price(self, price):
        try:
            if price is not None and self.discount_percentage:
                price = Decimal(price)
                discount = Decimal(self.discount_percentage or 0)
                if discount > 0:
                    discount_amount = (price * discount) / Decimal(100)
                    return price - discount_amount
            return price
        except (InvalidOperation, TypeError, ValueError):
            return price

    def discounted_price_monthly(self):
        return self.get_discounted_price(self.price_monthly)

    def discounted_price_yearly(self):
        return self.get_discounted_price(self.price_yearly) if self.price_yearly else None
