import uuid

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


class TimeStampedModel(models.Model):
    """Abstract base with created/updated timestamps."""

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

    class Meta:
        abstract = True


class ProductCategory(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=120, unique=True)
    slug = models.SlugField(max_length=140, unique=True)
    description = models.TextField(blank=True)
    display_order = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["display_order", "name"]
        verbose_name_plural = "Product categories"

    def __str__(self) -> str:
        return self.name


class Product(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    category = models.ForeignKey(
        ProductCategory,
        related_name="products",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    name = models.CharField(max_length=160)
    slug = models.SlugField(max_length=180, unique=True)
    short_description = models.CharField(max_length=280, blank=True)
    description = models.TextField(blank=True)
    ingredients = models.TextField(blank=True)
    allergens = models.CharField(
        max_length=280, blank=True, help_text="Comma-separated allergen labels."
    )
    price = models.DecimalField(max_digits=8, decimal_places=2)
    inventory_quantity = models.PositiveIntegerField(default=0)
    max_per_order = models.PositiveIntegerField(default=6)
    is_active = models.BooleanField(default=True)
    is_featured = models.BooleanField(default=False)
    hero_image = models.ImageField(upload_to="products/hero/", blank=True)

    class Meta:
        ordering = ["name"]

    def __str__(self) -> str:
        return self.name

    @property
    def is_available(self) -> bool:
        return self.is_active and self.inventory_quantity > 0


class DeliveryZone(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    label = models.CharField(max_length=120)
    postal_code = models.CharField(max_length=10, db_index=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["postal_code"]
        unique_together = ("postal_code", "label")

    def __str__(self) -> str:
        return f"{self.label} ({self.postal_code})"


class DeliveryOverrideCode(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    code = models.CharField(max_length=32, unique=True)
    label = models.CharField(max_length=120)
    message_to_customer = models.CharField(max_length=240, blank=True)
    max_uses = models.PositiveIntegerField(default=0, help_text="0 = unlimited")
    usage_count = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["code"]

    def __str__(self) -> str:
        return self.code

    def can_use(self) -> bool:
        if not self.is_active:
            return False
        if self.max_uses and self.usage_count >= self.max_uses:
            return False
        return True


class Order(TimeStampedModel):
    class FulfillmentMethod(models.TextChoices):
        PICKUP = "pickup", "Pickup"
        DELIVERY = "delivery", "Delivery"

    class Status(models.TextChoices):
        DRAFT = "draft", "Draft"
        PENDING = "pending", "Pending"
        CONFIRMED = "confirmed", "Confirmed"
        IN_PRODUCTION = "in_production", "In Production"
        READY = "ready", "Ready"
        COMPLETED = "completed", "Completed"
        CANCELLED = "cancelled", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    customer_name = models.CharField(max_length=160)
    customer_email = models.EmailField()
    customer_phone = models.CharField(max_length=32, blank=True)
    fulfillment_method = models.CharField(
        max_length=16, choices=FulfillmentMethod.choices, db_index=True
    )
    status = models.CharField(
        max_length=16, choices=Status.choices, default=Status.PENDING, db_index=True
    )
    scheduled_date = models.DateField(null=True, blank=True)
    scheduled_time_slot = models.CharField(max_length=64, blank=True)
    delivery_address_line1 = models.CharField(max_length=160, blank=True)
    delivery_address_line2 = models.CharField(max_length=160, blank=True)
    delivery_city = models.CharField(max_length=80, blank=True)
    delivery_state = models.CharField(max_length=32, blank=True)
    delivery_postal_code = models.CharField(max_length=16, blank=True)
    delivery_override_code = models.ForeignKey(
        DeliveryOverrideCode,
        related_name="orders",
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )
    subtotal_amount = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        validators=[MinValueValidator(0)],
    )
    tax_amount = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        validators=[MinValueValidator(0)],
    )
    delivery_fee_amount = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        validators=[MinValueValidator(0)],
    )
    discount_amount = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        validators=[MinValueValidator(0)],
    )
    total_amount = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        validators=[MinValueValidator(0)],
    )
    notes = models.TextField(blank=True)

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

    def __str__(self) -> str:
        return f"Order {self.id}"


class OrderItem(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE)
    product = models.ForeignKey(
        Product, related_name="order_items", on_delete=models.SET_NULL, null=True
    )
    product_name = models.CharField(max_length=160)
    product_slug = models.SlugField(max_length=180)
    unit_price = models.DecimalField(max_digits=8, decimal_places=2)
    quantity = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])
    line_subtotal = models.DecimalField(max_digits=8, decimal_places=2, default=0)

    class Meta:
        ordering = ["product_name"]

    def __str__(self) -> str:
        return f"{self.product_name} x{self.quantity}"
