from django import forms
from django.core.exceptions import ValidationError

from sales.models import FlatSale, Installment


class FlatSaleForm(forms.ModelForm):
    class Meta:
        model = FlatSale
        fields = ["flat", "buyer_name", "buyer_mobile", "buyer_address", "sale_price", "booking_money", "sale_date", "notes"]
        widgets = {
            "flat": forms.Select(attrs={"class": "form-select"}),
            "buyer_name": forms.TextInput(attrs={"class": "form-control"}),
            "buyer_mobile": forms.TextInput(attrs={"class": "form-control"}),
            "buyer_address": forms.Textarea(attrs={"class": "form-control", "rows": 2}),
            "sale_price": forms.NumberInput(attrs={"class": "form-control", "step": "0.01"}),
            "booking_money": forms.NumberInput(attrs={"class": "form-control", "step": "0.01"}),
            "sale_date": forms.DateInput(attrs={"class": "form-control", "type": "date"}),
            "notes": forms.Textarea(attrs={"class": "form-control", "rows": 3}),
        }

    def __init__(self, *args, project=None, instance=None, **kwargs):
        super().__init__(*args, instance=instance, **kwargs)
        self.project = project
        if project:
            qs = self.fields["flat"].queryset.filter(floor__building__project=project)
            if instance:
                qs = qs | self.fields["flat"].queryset.filter(pk=instance.flat_id)
            self.fields["flat"].queryset = qs.distinct().order_by("floor__building__name", "floor__floor_number", "flat_no")

    def clean(self):
        cleaned = super().clean()
        flat = cleaned.get("flat")
        sale_price = cleaned.get("sale_price")
        booking = cleaned.get("booking_money")
        if flat and self.project and str(flat.floor.building.project_id) != str(self.project.id):
            raise ValidationError("Selected unit does not belong to the active company.")
        if sale_price is not None and sale_price <= 0:
            self.add_error("sale_price", "Sale price must be greater than zero.")
        if booking is not None and booking < 0:
            self.add_error("booking_money", "Booking money cannot be negative.")
        if sale_price is not None and booking is not None and booking > sale_price:
            self.add_error("booking_money", "Booking money cannot exceed sale price.")
        if flat and not self.instance.pk and hasattr(flat, "sale"):
            raise ValidationError("This unit already has a sale record.")
        return cleaned


class InstallmentForm(forms.ModelForm):
    class Meta:
        model = Installment
        fields = ["date", "amount", "payment_method", "remarks"]
        widgets = {
            "date": forms.DateInput(attrs={"class": "form-control", "type": "date"}),
            "amount": forms.NumberInput(attrs={"class": "form-control", "step": "0.01"}),
            "payment_method": forms.Select(attrs={"class": "form-select"}),
            "remarks": forms.TextInput(attrs={"class": "form-control"}),
        }
