from random import randint

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django_ledger.models import EntityModel, VendorModel, CustomerModel, UnitOfMeasureModel
from django.utils.translation import gettext_lazy as _
from . import models


@receiver(post_save, sender=models.CarReservation)
def update_car_status_on_reservation(sender, instance, created, **kwargs):
    if created:
        car = instance.car
        car.status = models.CarStatusChoices.RESERVED
        car.save()


@receiver(post_delete, sender=models.CarReservation)
def update_car_status_on_reservation_delete(sender, instance, **kwargs):
    car = instance.car
    if not car.get_current_reservation():
        car.status = models.CarStatusChoices.AVAILABLE
        car.save()


# Create Entity
@receiver(post_save, sender=models.Dealer)
def create_ledger_entity(sender, instance, created, **kwargs):
    if created:
        entity = EntityModel.objects.create(
            name=instance.name,
            admin=instance.user,
            address_1=instance.address,
            fy_start_month=1,
            accrual_method=True,
            depth=0,
        )

        default_coa = entity.create_chart_of_accounts(assign_as_default=True,
                                                      commit=True,
                                                      coa_name=_("Chart of Accounts"))
        # entity.create_account(
        #     coa_model=coa,
        #     code=1010,
        #     role='asset_ca_cash',
        #     name=_('Cash'),
        #     balance_type="debit",
        # )
        # entity.create_account(
        #     coa_model=coa,
        #     code=1200,
        #     role='asset_ca_inv',
        #     name=_('Inventory'),
        #     balance_type="debit",
        #     active=True)


        if default_coa:
            entity.populate_default_coa(activate_accounts=True, coa_model=default_coa)

        uom_name = _("Unit")
        unit_abbr = _("U")

        entity.create_uom(uom_name, unit_abbr)

        print(f"Ledger entity created for Dealer: {instance.name}")


# # Create Vendor
@receiver(post_save, sender=models.Vendor)
def create_ledger_vendor(sender, instance, created, **kwargs):

    if created:
        entity = EntityModel.objects.filter(name=instance.dealer.name).first()

        entity.create_vendor(
            vendor_name=instance.name,
            vendor_number=instance.crn,
            address_1=instance.address,
            phone=instance.phone_number,
            tax_id_number=instance.vrn,
            active=True,
            hidden=False,
            additional_info={
                "arabic_name": instance.arabic_name,
                "contact_person": instance.contact_person,
            })


        print(f"VendorModel created for Vendor: {instance.name}")


@receiver(post_save, sender=models.Customer)
def create_customer(sender, instance, created, **kwargs):

    if created:
        entity = EntityModel.objects.filter(name=instance.dealer.name).first()
        name = f"{instance.first_name} {instance.middle_name} {instance.last_name}"

        entity.create_customer(
            customer_name=name,
            customer_number=instance.national_id,
            address_1=instance.address,
            phone=instance.phone_number,
            email=instance.email,
            sales_tax_rate=0.15,
            active=True,
            hidden=False,
            additional_info={}
        )

        print(f"Customer created: {name}")


# Create Item
@receiver(post_save, sender=models.Car)
def create_item_model(sender, instance, created, **kwargs):
    item_name = f"{instance.year} - {instance.id_car_make} - {instance.id_car_model} - {instance.id_car_trim}"
    uom_name = _("Car")
    unit_abbr = _("C")

    uom, uom_created = UnitOfMeasureModel.objects.get_or_create(
        name=uom_name,
        unit_abbr=unit_abbr
    )

    if uom_created:
        print(f"UOM created: {uom_name}")
    else:
        print(f"Using existing UOM: {uom_name}")

    entity = EntityModel.objects.filter(name=instance.dealer.name).first()

    inventory_account = AccountModel.objects.first()
    cogs_account = AccountModel.objects.first()
    earnings_account = AccountModel.objects.first()

    entity.create_i

    item = ItemModel.objects.create(
        entity=entity,
        uom=uom,
        name=item_name,
        item_role=ItemModelAbstract.ITEM_ROLE_INVENTORY,
        item_type=ItemModelAbstract.ITEM_TYPE_MATERIAL,
        item_id=instance.vin,
        sold_as_unit=True,
        inventory_received=1.00,
        inventory_received_value=0.00,
        inventory_account=inventory_account,
        for_inventory=True,
        is_product_or_service=True,
        cogs_account=cogs_account,
        earnings_account=earnings_account,
        is_active=True,
        additional_info={
            "remarks": instance.remarks,
            "status": instance.status,
            "stock_type": instance.stock_type,
            "mileage": instance.mileage,
        },
    )

    print(f"ItemModel {'created' if created else 'updated'} for Car: {item.name}")
#
#
# # update price - CarFinance
# @receiver(post_save, sender=CarFinance)
# def update_item_model_cost(sender, instance, created, **kwargs):
#
#     ItemModel.objects.filter(item_id=instance.car.vin).update(
#         inventory_received_value=instance.cost_price,
#         default_amount=instance.cost_price,
#     )
#     print(f"Inventory item updated with CarFinance data for Car: {instance.car}")
