from decimal import Decimal

from apps.agreement.models import Agreement
from django.db import models
from django.utils.translation import gettext_lazy as _


class Services(models.Model):
    FLOOR_CHOICES = (
        (0, "UnderGround"),
        (1, "First floor"),
        (2, "Second Floor"),
        (3, "Third Floor"),
        (4, "Fourth Floor"),
        (5, "Fifth Floor"),
    )

    MONTH_CHOICES = (
        (1, "حمل"),
        (2, "ثور"),
        (3, "جوزا"),
        (4, "سرطان"),
        (5, "اسد"),
        (6, "سنبله"),
        (7, "میزان"),
        (8, "عقرب"),
        (9, "قوس"),
        (10, "جدی"),
        (11, "دلو"),
        (12, "حوت"),
    )

    floor = models.CharField(_("Floor"), choices=FLOOR_CHOICES, max_length=50)
    time = models.CharField(_("Time"), choices=MONTH_CHOICES, max_length=250)
    year = models.CharField(max_length=255)
    total = models.DecimalField(
        _("Total"), max_digits=10, decimal_places=2, default=Decimal("0.00")
    )
    is_approved = models.BooleanField(default=False)
    customers_list = models.JSONField(default=dict)
    total_taken = models.DecimalField(
        _("Total Taken"), max_digits=10, decimal_places=2, default=Decimal("0.00")
    )
    total_remainder = models.DecimalField(
        _("Total Remainder"), max_digits=10, decimal_places=2, default=Decimal("0.00")
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = _("Service")
        verbose_name_plural = _("Services")

    def get_customers_list(self, customers_taken_data=None):
        agreements = Agreement.objects.filter(status="Active", floor=self.floor)

        customers_data = {}
        total_rent = Decimal("0.00")
        total_taken = Decimal("0.00")
        total_remainder = Decimal("0.00")

        for agreement in agreements:
            customer = agreement.customer
            service = agreement.service
            is_approved = self.is_approved

            taken = (
                Decimal(customers_taken_data.get(str(customer.id), 0.0))
                if customers_taken_data
                else Decimal("0.00")
            )
            remainder = service - taken

            customer_data = {
                "service": float(service),
                "taken": float(taken),
                "remainder": float(remainder),
                "is_approved": is_approved,
            }

            customers_data[str(customer.id)] = customer_data
            total_rent += service
            total_taken += taken
            total_remainder += remainder

        self.total = total_rent
        self.total_taken = total_taken
        self.total_remainder = total_remainder

        return customers_data

    def save(self, *args, **kwargs):
        if not self.pk:
            self.customers_list = self.get_customers_list()

        super().save(*args, **kwargs)
