from decimal import Decimal

from django.db import models
from django.utils.translation import gettext_lazy as _


class Staff(models.Model):
    class Position(models.TextChoices):
        GARD = "Gard", _("Gard")
        CLEANER = "Cleaner", _("Cleaner")
        ELECTRICAL = "Electrical", _("Electrical")
        MANAGER = "Manager", _("Manager")
        COOKER = "Cooker", _("Cooker")
        OTHER = "Other", _("Other")

    class Status(models.TextChoices):
        ACTIVE = "Active", _("Active")
        INACTIVE = "Inactive", _("Inactive")

    name = models.CharField(_("Name"), max_length=250)
    father_name = models.CharField(_("Father Name"), max_length=250)
    nic = models.IntegerField(_("NIC"))
    photo = models.ImageField(upload_to="staff/images")
    address = models.CharField(_("Address"), max_length=250)
    position = models.CharField(_("Position"), choices=Position.choices, max_length=250)
    salary = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)
    status = models.CharField(_("Status"), choices=Status.choices, max_length=250)

    def __str__(self):
        return f"{self.name} ({self.position})"


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

    month = 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")
    )
    customers_list = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def get_customers_list(self):
        """Populate the customers list from active staff."""
        active_staff = Staff.objects.filter(status=Staff.Status.ACTIVE)
        customers_data = {}
        total_salary = Decimal("0.00")

        for staff in active_staff:
            taken = Decimal("0.00")
            remainder = Decimal("0.00")

            # Adding salary details for each staff member
            customer_data = {
                "salary": float(staff.salary),  # Using float for compatibility
                "taken": float(taken),  # Default taken value is 0
                "remainder": float(remainder),  # Default remainder is 0
            }

            customers_data[staff.id] = customer_data
            total_salary += staff.salary

        return customers_data, total_salary

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

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