from django import forms

from .constants import PAYMENT_METHOD_CHOICES, PRODUCT_PRICE
from .models import Order


class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = [
            "full_name",
            "phone",
            "whatsapp_number",
            "address",
            "district",
            "state",
            "pincode",
            "quantity",
            "payment_method",
            "order_notes",
        ]
        widgets = {
            "address": forms.Textarea(attrs={"rows": 3}),
            "order_notes": forms.Textarea(attrs={"rows": 3}),
            "payment_method": forms.Select(choices=PAYMENT_METHOD_CHOICES),
        }

    def clean_phone(self):
        phone = self.cleaned_data["phone"].strip()
        if not (phone.isdigit() and len(phone) == 10 and phone[0] in "6789"):
            raise forms.ValidationError("Enter a valid 10-digit Indian phone number.")
        return phone

    def clean_whatsapp_number(self):
        number = self.cleaned_data.get("whatsapp_number", "").strip()
        if number and not (number.isdigit() and len(number) == 10 and number[0] in "6789"):
            raise forms.ValidationError("Enter a valid WhatsApp number.")
        return number

    def clean_pincode(self):
        pincode = self.cleaned_data["pincode"].strip()
        if not (pincode.isdigit() and len(pincode) == 6):
            raise forms.ValidationError("Enter a valid 6-digit pincode.")
        return pincode

    def clean_quantity(self):
        quantity = self.cleaned_data["quantity"]
        if quantity < 1 or quantity > 99:
            raise forms.ValidationError("Quantity must be between 1 and 99.")
        return quantity

    def save(self, commit=True):
        order = super().save(commit=False)
        order.total_amount = PRODUCT_PRICE * order.quantity
        if commit:
            order.save()
        return order
