import re

from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

from account.models import Organization, UserProfile

User = get_user_model()

class RegistrationForm(UserCreationForm):
    company_name = forms.CharField(
        label="Bedrijfsnaam",
        max_length=255,
        widget=forms.TextInput(attrs={
            'placeholder': 'Mijn Bouwbedrijf B.V.',
        })
    )

    email = forms.EmailField(
        required=True,
        widget=forms.EmailInput(attrs={
            'placeholder': 'naam@bedrijf.nl'
        })
    )

    class Meta:
        model = User
        fields = ('email',)

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

        for _field_name, field in self.fields.items():
            field.widget.attrs.update({
                'class': 'block w-full appearance-none rounded-md border border-gray-300 px-3 py-3 placeholder-gray-400 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500 sm:text-sm'
            })

        self.fields['password1'].help_text = "Gebruik minimaal 8 tekens."


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

        self.fields['username'].label = "E-mailadres"
        self.fields['username'].widget.attrs.update({
            'placeholder': 'naam@bedrijf.nl',
            'class': 'block w-full appearance-none rounded-md border border-gray-300 px-3 py-3 placeholder-gray-400 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500 sm:text-sm'
        })

        self.fields['password'].label = "Wachtwoord"
        self.fields['password'].widget.attrs.update({
            'class': 'block w-full appearance-none rounded-md border border-gray-300 px-3 py-3 placeholder-gray-400 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500 sm:text-sm'
        })

class OrganizationForm(forms.ModelForm):
    class Meta:
        model = Organization
        fields = ['name', 'slug', 'address', 'postal_code', 'city', 'email', 'kvk_number', 'vat_number', 'iban']
        widgets = {
            field: forms.TextInput(attrs={
                'class': 'mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm'
            }) for field in ['name', 'slug', 'kvk_number', 'vat_number', 'iban']
        }

    def clean_postal_code(self):
        postal_code = self.cleaned_data.get('postal_code')
        if postal_code:
            postal_code = postal_code.replace(" ", "").upper()
            # Nederlandse postcode check: 4 cijfers, 2 letters
            if not re.match(r'^[1-9][0-9]{3}[A-Z]{2}$', postal_code):
                raise forms.ValidationError("Voer een geldige Nederlandse postcode in (bijv. 9648JX).")
            # We slaan hem netjes geformatteerd op: 1234 AB
            return f"{postal_code[:4]} {postal_code[4:]}"
        return postal_code

    def clean_kvk_number(self):
        kvk = self.cleaned_data.get('kvk_number')
        if kvk:
            # Use [0-9] to strictly enforce ASCII digits. \d matches unicode digits too.
            if not re.match(r'^[0-9]{8}$', kvk):
                raise forms.ValidationError("Een KvK-nummer moet precies 8 cijfers bevatten.")
        return kvk

    def clean_vat_number(self):
        vat = self.cleaned_data.get('vat_number')
        if vat:
            # Format: NL + 9 cijfers + B + 2 cijfers
            pattern = r'^NL\d{9}B\d{2}$'
            if not re.match(pattern, vat):
                raise forms.ValidationError("Voer een geldig BTW-nummer in (bijv. NL123456789B01).")
        return vat

    def clean_iban(self):
        iban = self.cleaned_data.get('iban')
        if iban:
            iban = iban.replace(" ", "").upper()
            if not re.match(r'^[A-Z]{2}\d{2}[A-Z]{4}\d{10}$', iban):
                raise forms.ValidationError("Voer een geldig IBAN nummer in.")
        return iban

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['first_name', 'last_name']
        labels = {
            'first_name': 'Voornaam',
            'last_name': 'Achternaam',
        }
        widgets = {
            'first_name': forms.TextInput(attrs={
                'class': 'mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm'
            }),
            'last_name': forms.TextInput(attrs={
                'class': 'mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm'
            }),
        }
