from django import forms
from management.models import Customer
from django.forms import ModelForm
from phonenumbers import parse, is_valid_number, format_number, PhoneNumberFormat, NumberParseException
from django import forms
from django.utils.translation import gettext_lazy as _


class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = "__all__"
        widgets = {
            'phone_number': forms.TextInput(attrs={'placeholder': 'e.g., +62813xxxxxxx'}),
        }

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get("phone_number")
        if not phone_number:
            raise forms.ValidationError("Phone number is required and cannot be empty.")
        try:
            if not phone_number.startswith('+'):
                phone_number = '+62' + phone_number.lstrip('0')
            parsed_phone = parse(phone_number, "ID")
            if not is_valid_number(parsed_phone):
                raise ValueError("Invalid phone number")
            # Return standardized phone number
            return format_number(parsed_phone, PhoneNumberFormat.E164)
        except NumberParseException:
            raise ValueError(f"Invalid phone number format: {phone_number}")