import uuid
from decimal import Decimal
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from apps.localization.bs_calendar import ad_to_bs
from apps.localization.tax import validate_nepal_pan


class VendorProfile(models.Model):
    class Category(models.TextChoices):
        MATERIALS = "MATERIALS", "Construction Materials"
        EQUIPMENT = "EQUIPMENT", "Machinery & Equipment"
        CONTRACTOR = "CONTRACTOR", "Subcontractors & Job Work"
        SERVICES = "SERVICES", "Professional & Site Services"

    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending Approval"
        APPROVED = "APPROVED", "Approved"
        SUSPENDED = "SUSPENDED", "Suspended"
        BLACKLISTED = "BLACKLISTED", "Blacklisted"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="vendors")
    party = models.OneToOneField("accounting.Party", on_delete=models.PROTECT, related_name="vendor_profile")
    vendor_category = models.CharField(max_length=20, choices=Category.choices, default=Category.MATERIALS)
    registration_no = models.CharField(max_length=64, blank=True)
    pan_vat_no = models.CharField(max_length=20, blank=True, db_index=True)
    bank_name = models.CharField(max_length=120, blank=True)
    bank_account_no = models.CharField(max_length=48, blank=True)
    bank_branch = models.CharField(max_length=100, blank=True)
    quality_rating = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal("4.50"))
    delivery_rating = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal("4.50"))
    price_rating = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal("4.50"))
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING, db_index=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "vendors"
        ordering = ["party__name"]

    def clean(self):
        if self.pan_vat_no:
            if not validate_nepal_pan(self.pan_vat_no):
                raise ValidationError({"pan_vat_no": "Nepal PAN/VAT must be a 9-digit number."})
            dup = VendorProfile.objects.filter(company=self.company, pan_vat_no=self.pan_vat_no).exclude(pk=self.pk)
            if dup.exists():
                raise ValidationError({"pan_vat_no": f"Duplicate vendor PAN/VAT {self.pan_vat_no} already registered."})


class VendorContact(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(VendorProfile, on_delete=models.CASCADE, related_name="contacts")
    name = models.CharField(max_length=120)
    designation = models.CharField(max_length=80, blank=True)
    phone = models.CharField(max_length=40, blank=True)
    email = models.EmailField(blank=True)
    is_primary = models.BooleanField(default=False)

    class Meta:
        db_table = "vendor_contacts"


class VendorDocument(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(VendorProfile, on_delete=models.CASCADE, related_name="documents")
    doc_type = models.CharField(max_length=64)
    doc_number = models.CharField(max_length=64, blank=True)
    file_ref = models.CharField(max_length=255, blank=True)
    issue_date = models.DateField(null=True, blank=True)
    expiry_date = models.DateField(null=True, blank=True)

    class Meta:
        db_table = "vendor_documents"


class VendorRating(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vendor = models.ForeignKey(VendorProfile, on_delete=models.CASCADE, related_name="ratings")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    score = models.DecimalField(max_digits=3, decimal_places=2)
    comments = models.CharField(max_length=255, blank=True)
    rated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    rated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "vendor_ratings"


class PurchaseRequisition(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        DEPT_APPROVED = "DEPT_APPROVED", "Department Approved"
        BUDGET_CHECKED = "BUDGET_CHECKED", "Budget Validated"
        APPROVED = "APPROVED", "Procurement Approved"
        CONVERTED = "CONVERTED", "Converted to RFQ / PO"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="purchase_requisitions")
    requisition_no = models.CharField(max_length=40)
    requisition_date = models.DateField()
    bs_date = models.CharField(max_length=16, blank=True)
    required_delivery_date = models.DateField()
    department = models.ForeignKey("accounting.Department", on_delete=models.PROTECT, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    priority = models.CharField(max_length=16, default="NORMAL")
    budget_warning = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.DRAFT, db_index=True)
    requested_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="requested_prs")
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_prs"
    )
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "purchase_requisitions"
        unique_together = [("company", "requisition_no")]
        ordering = ["-requisition_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.requisition_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.requisition_date).isoformat()
        super().save(*args, **kwargs)


class PurchaseRequisitionLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    requisition = models.ForeignKey(PurchaseRequisition, on_delete=models.CASCADE, related_name="lines")
    item = models.ForeignKey("inventory.ItemMaster", on_delete=models.PROTECT, null=True, blank=True)
    description = models.CharField(max_length=220)
    unit = models.CharField(max_length=24, default="Bags")
    requested_qty = models.DecimalField(max_digits=14, decimal_places=3)
    estimated_rate = models.DecimalField(max_digits=14, decimal_places=2)
    estimated_total = models.DecimalField(max_digits=18, decimal_places=2)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    budget_line = models.ForeignKey("budgeting.BudgetLine", on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "purchase_requisition_lines"


class RFQ(models.Model):
    class Status(models.TextChoices):
        OPEN = "OPEN", "Open for Quotations"
        EVALUATED = "EVALUATED", "Quotations Evaluated"
        AWARDED = "AWARDED", "Awarded to PO"
        CLOSED = "CLOSED", "Closed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="rfqs")
    rfq_no = models.CharField(max_length=40)
    rfq_date = models.DateField()
    deadline = models.DateField()
    requisition = models.ForeignKey(PurchaseRequisition, on_delete=models.SET_NULL, null=True, blank=True, related_name="rfqs")
    invited_vendors = models.ManyToManyField(VendorProfile, blank=True, related_name="rfqs")
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN)
    notes = models.TextField(blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)

    class Meta:
        db_table = "rfqs"
        unique_together = [("company", "rfq_no")]
        ordering = ["-rfq_date"]


class VendorQuotation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    rfq = models.ForeignKey(RFQ, on_delete=models.CASCADE, related_name="quotations")
    vendor = models.ForeignKey(VendorProfile, on_delete=models.PROTECT, related_name="quotations")
    quotation_ref = models.CharField(max_length=64)
    quoted_date = models.DateField()
    delivery_days = models.PositiveSmallIntegerField(default=7)
    payment_terms_days = models.PositiveSmallIntegerField(default=30)
    freight_charge = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    tax_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    discount_amount = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    subtotal_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_landed_cost = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    technical_compliant = models.BooleanField(default=True)
    warranty_months = models.PositiveSmallIntegerField(default=0)
    attachment_ref = models.CharField(max_length=255, blank=True)
    is_selected = models.BooleanField(default=False)

    class Meta:
        db_table = "vendor_quotations"
        unique_together = [("rfq", "vendor")]
        ordering = ["total_landed_cost"]


class VendorQuotationLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    quotation = models.ForeignKey(VendorQuotation, on_delete=models.CASCADE, related_name="lines")
    item = models.ForeignKey("inventory.ItemMaster", on_delete=models.PROTECT, null=True, blank=True)
    description = models.CharField(max_length=220)
    quantity = models.DecimalField(max_digits=14, decimal_places=3)
    unit_rate = models.DecimalField(max_digits=14, decimal_places=2)
    line_total = models.DecimalField(max_digits=18, decimal_places=2)

    class Meta:
        db_table = "quotation_lines"


class QuotationComparison(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    rfq = models.OneToOneField(RFQ, on_delete=models.CASCADE, related_name="comparison")
    recommended_vendor = models.ForeignKey(VendorProfile, on_delete=models.PROTECT)
    justification = models.TextField()
    compared_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    compared_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "quotation_comparisons"


class PurchaseOrder(models.Model):
    class OrderKind(models.TextChoices):
        STANDARD = "STANDARD", "Standard Purchase Order"
        PROJECT = "PROJECT", "Project Material Order"
        SERVICE = "SERVICE", "Service Order"
        EQUIPMENT_RENTAL = "EQUIPMENT_RENTAL", "Equipment Rental Order"
        SUBCONTRACT = "SUBCONTRACT", "Subcontractor Work Order"
        BLANKET = "BLANKET", "Blanket / Rate Agreement"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted"
        APPROVED = "APPROVED", "Approved & Committed"
        PARTIAL = "PARTIAL", "Partially Received / Billed"
        CLOSED = "CLOSED", "Closed"
        CANCELLED = "CANCELLED", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="purchase_orders")
    po_number = models.CharField(max_length=40)
    po_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    order_kind = models.CharField(max_length=20, choices=OrderKind.choices, default=OrderKind.PROJECT)
    vendor = models.ForeignKey(VendorProfile, on_delete=models.PROTECT, related_name="purchase_orders")
    requisition = models.ForeignKey(PurchaseRequisition, on_delete=models.SET_NULL, null=True, blank=True)
    rfq = models.ForeignKey(RFQ, on_delete=models.SET_NULL, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    payment_terms_days = models.PositiveSmallIntegerField(default=30)
    subtotal_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tax_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    justification = models.TextField(blank=True)
    amendment_count = models.PositiveSmallIntegerField(default=0)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_pos")
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_pos"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "purchase_orders"
        unique_together = [("company", "po_number")]
        ordering = ["-po_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.po_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.po_date).isoformat()
        super().save(*args, **kwargs)


class PurchaseOrderLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE, related_name="lines")
    item = models.ForeignKey("inventory.ItemMaster", on_delete=models.PROTECT, null=True, blank=True)
    description = models.CharField(max_length=220)
    unit = models.CharField(max_length=24, default="Units")
    ordered_qty = models.DecimalField(max_digits=14, decimal_places=3)
    received_qty = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    billed_qty = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    unit_rate = models.DecimalField(max_digits=14, decimal_places=2)
    tax_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("13.00"))
    line_total = models.DecimalField(max_digits=18, decimal_places=2)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    budget_line = models.ForeignKey("budgeting.BudgetLine", on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "purchase_order_lines"


class ThreeWayMatch(models.Model):
    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending Review"
        VARIANCE_HOLD = "VARIANCE_HOLD", "Variance Exception Hold"
        MATCHED_POSTED = "MATCHED_POSTED", "Matched & Posted to GL"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="three_way_matches")
    purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.PROTECT, related_name="matches")
    grn = models.ForeignKey("inventory.GoodsReceiptNote", on_delete=models.PROTECT, related_name="matches")
    supplier_invoice_no = models.CharField(max_length=64)
    invoice_date = models.DateField()
    ordered_amount = models.DecimalField(max_digits=18, decimal_places=2)
    received_amount = models.DecimalField(max_digits=18, decimal_places=2)
    billed_amount = models.DecimalField(max_digits=18, decimal_places=2)
    tax_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tds_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    variance_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    within_tolerance = models.BooleanField(default=True)
    variance_reason = models.CharField(max_length=255, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "purchase_matches"
        ordering = ["-created_at"]

