from django import forms
from .models import OrderItem, Order, StockReception
from inventory.models import Product


class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ['supplier']

    def __init__(self, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        self.fields['supplier'].widget.attrs.update({'class': 'form-control'})


class OrderItemForm(forms.ModelForm):
    product = forms.ModelChoiceField(
        queryset=Product.objects.all(),
        widget=forms.Select(attrs={'class': 'form-control'}),
        empty_label="-- Select a Product --"
    )
    quantity_ordered = forms.IntegerField(
        min_value=1,
        widget=forms.NumberInput(attrs={'class': 'form-control'}),
        label="Quantity Ordered"
    )
    buying_price = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        widget=forms.NumberInput(attrs={'class': 'form-control'}),
        label="Buying Price"
    )

    class Meta:
        model = OrderItem
        fields = ['product', 'quantity_ordered', 'buying_price']

    def __init__(self, *args, **kwargs):
        super(OrderItemForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.fields['buying_price'].initial = self.instance.product.buying_price
        else:
            self.fields['buying_price'].initial = None


class StockReceptionForm(forms.ModelForm):
    class Meta:
        model = StockReception
        fields = [
            'product', 'supplier', 'quantity_received', 'buying_price',
            'selling_price', 'expiry_date', 'batch_code', 'received_date', 'notes'
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Add consistent styling for better user experience
        for field in self.fields.values():
            field.widget.attrs.update({'class': 'form-control'})

        # Add placeholders for better user guidance
        self.fields['product'].widget.attrs.update({'placeholder': '-- Select a Product --'})
        self.fields['supplier'].widget.attrs.update({'placeholder': '-- Select a Supplier --'})
        self.fields['quantity_received'].widget.attrs.update({'placeholder': 'Enter quantity received'})
        self.fields['buying_price'].widget.attrs.update({'placeholder': 'Enter buying price per unit'})
        self.fields['selling_price'].widget.attrs.update({'placeholder': 'Enter selling price per unit'})
        self.fields['expiry_date'].widget.attrs.update({'placeholder': 'Enter expiry date (optional)'})
        self.fields['batch_code'].widget.attrs.update({'placeholder': 'Enter batch code (optional)'})
        self.fields['notes'].widget.attrs.update({'placeholder': 'Add any additional notes (optional)'})

    def clean_quantity_received(self):
        quantity_received = self.cleaned_data.get('quantity_received')
        if quantity_received <= 0:
            raise forms.ValidationError("Quantity received must be greater than 0.")
        return quantity_received

    def clean_buying_price(self):
        buying_price = self.cleaned_data.get('buying_price')
        if buying_price <= 0:
            raise forms.ValidationError("Buying price must be greater than 0.")
        return buying_price

    def clean_selling_price(self):
        selling_price = self.cleaned_data.get('selling_price')
        buying_price = self.cleaned_data.get('buying_price')
        if selling_price and selling_price <= buying_price:
            raise forms.ValidationError("Selling price must be greater than the buying price.")
        return selling_price
