from django import forms
from decimal import Decimal
from .models import Customer, Sale, SaleItem, Payment


class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = ["name", "phone", "email", "address"]
        widgets = {
            "name": forms.TextInput(attrs={"class": "form-control"}),
            "phone": forms.TextInput(attrs={"class": "form-control"}),
            "email": forms.EmailInput(attrs={"class": "form-control"}),
            "address": forms.Textarea(attrs={"class": "form-control", "rows": 2}),
        }


class SaleItemForm(forms.ModelForm):
    # Sale quantities are whole units only (no decimal quantities).
    quantity = forms.IntegerField(
        min_value=1,
        widget=forms.NumberInput(attrs={
            "class": "form-control", "step": "1", "min": "1",
            "inputmode": "numeric", "pattern": "[0-9]*"
        })
    )

    class Meta:
        model = SaleItem
        fields = ["product", "quantity", "sell_price"]
        widgets = {
            "product": forms.Select(attrs={"class": "form-control"}),
            "sell_price": forms.NumberInput(
                attrs={"class": "form-control", "step": "0.01", "min": "0"}
            ),
        }


SaleItemFormSet = forms.inlineformset_factory(
    Sale,
    SaleItem,
    form=SaleItemForm,
    extra=1,
    can_delete=True,
)


class SaleForm(forms.ModelForm):
    paid_amount = forms.DecimalField(
        required=False,
        min_value=0,
        initial=0,
        widget=forms.NumberInput(attrs={
            "class": "form-control", "step": "0.01", "min": "0",
            "placeholder": "0.00", "id": "id_paid_amount"
        }),
        help_text="Amount received now. Leave 0 for a fully due invoice.",
    )

    payment_reference = forms.CharField(
        required=False,
        max_length=255,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "bKash/Nagad/Card transaction or reference number",
            "id": "id_payment_reference",
        }),
        help_text="Optional. Useful for bKash, Nagad, Card, Bank Transfer, etc.",
    )

    class Meta:
        model = Sale
        fields = [
            "customer",
            "invoice_number",
            "date",
            "discount",
            "payment_method",
            "notes",
        ]
        widgets = {
            "customer": forms.Select(attrs={"class": "form-control"}),
            "invoice_number": forms.TextInput(
                attrs={"class": "form-control", "readonly": True}
            ),
            "date": forms.DateInput(
                attrs={"class": "form-control", "type": "date"}
            ),
            "discount": forms.NumberInput(
                attrs={"class": "form-control", "step": "0.01", "min": "0"}
            ),
            "payment_method": forms.Select(attrs={"class": "form-control"}),
            "notes": forms.Textarea(
                attrs={"class": "form-control", "rows": 2}
            ),
        }

    def clean_paid_amount(self):
        value = self.cleaned_data.get("paid_amount")
        return value if value is not None else Decimal("0")

    def __init__(self, *args, company=None, **kwargs):
        super().__init__(*args, **kwargs)
        if company is not None:
            self.fields["customer"].queryset = Customer.objects.filter(
                company=company, is_active=True
            )
