from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from .models import Profile, Role
from common.consts import UserRoles

User = get_user_model()

class CustomerForm(forms.ModelForm):
    """فرم برای افزودن مشترک جدید"""
    first_name = forms.CharField(
        max_length=150,
        label="نام",
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'نام'
        })
    )
    last_name = forms.CharField(
        max_length=150,
        label="نام خانوادگی",
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'نام خانوادگی'
        })
    )
    
    class Meta:
        model = Profile
        fields = [
            'phone_number_1', 'phone_number_2', 'national_code', 
            'address', 'card_number', 'account_number', 'bank_name'
        ]
        widgets = {
            'phone_number_1': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '09123456789'
            }),
            'phone_number_2': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '02112345678'
            }),
            'national_code': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '1234567890',
                'maxlength': '10',
                'required': 'required'
            }),
            'address': forms.Textarea(attrs={
                'class': 'form-control',
                'placeholder': 'آدرس کامل',
                'rows': '3'
            }),
            'card_number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'شماره کارت بانکی',
                'maxlength': '16'
            }),
            'account_number': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'شماره حساب بانکی',
                'maxlength': '20'
            }),
            'bank_name': forms.Select(attrs={
                'class': 'form-control',
                'placeholder': 'نام بانک',
            }),
        }
        labels = {
            'phone_number_1': 'تلفن ۱',
            'phone_number_2': 'تلفن ۲',
            'national_code': 'کد ملی',
            'address': 'آدرس',
            'card_number': 'شماره کارت',
            'account_number': 'شماره حساب',
            'bank_name': 'نام بانک',
        }

    def clean_national_code(self):
        national_code = self.cleaned_data.get('national_code')
        if national_code:
            # Check if user with this national code exists
            existing_user = User.objects.filter(username=national_code).first()
            if existing_user:
                # If we're editing and the user is the same, it's OK
                if self.instance and self.instance.user and existing_user == self.instance.user:
                    return national_code
                # Otherwise, it's a duplicate
                raise forms.ValidationError('این کد ملی قبلاً استفاده شده است.')
        return national_code

    def save(self, commit=True):
        # Check if this is an update (instance exists)
        if self.instance and self.instance.pk:
            # Update existing profile
            profile = super().save(commit=False)
            
            # Update user information
            user = profile.user
            user.first_name = self.cleaned_data['first_name']
            user.last_name = self.cleaned_data['last_name']
            user.save()
            
            # Set affairs, county, and broker from current user's profile
            if hasattr(self, 'request') and self.request.user.is_authenticated:
                current_user_profile = getattr(self.request.user, 'profile', None)
                if current_user_profile:
                    profile.affairs = current_user_profile.affairs
                    profile.county = current_user_profile.county
                    profile.broker = current_user_profile.broker
            
            if commit:
                profile.save()
                self.save_m2m()
            
            return profile
        else:
            # Create new profile
            # Get national code as username
            national_code = self.cleaned_data.get('national_code')
            if not national_code:
                raise forms.ValidationError('کد ملی الزامی است.')
            
            # Create User with default password
            user = User.objects.create_user(
                username=national_code,
                email='',  # Empty email
                password='sooha1234',  # Default password
                first_name=self.cleaned_data['first_name'],
                last_name=self.cleaned_data['last_name']
            )
            
            # Create Profile
            profile = super().save(commit=False)
            profile.user = user
            profile.owner = user
            
            # Set affairs, county, and broker from current user's profile
            if hasattr(self, 'request') and self.request.user.is_authenticated:
                current_user_profile = getattr(self.request.user, 'profile', None)
                if current_user_profile:
                    profile.affairs = current_user_profile.affairs
                    profile.county = current_user_profile.county
                    profile.broker = current_user_profile.broker
            
            if commit:
                profile.save()
                self.save_m2m()
                
                # Add customer role after profile is saved
                customer_role = Role.objects.filter(slug=UserRoles.CUSTOMER.value).first()
                if customer_role:
                    profile.roles.add(customer_role)
                else:
                    # Create customer role if it doesn't exist
                    customer_role = Role.objects.create(
                        name='مشترک',
                        slug=UserRoles.CUSTOMER.value
                    )
                    profile.roles.add(customer_role)
            
            return profile 