from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from userauth.models import User, AccessLevel
from django import forms
from django.contrib.auth import get_user_model
from doctor.models import Doctor, Technician
from patient.models import Patient
from .models import AccessLevel
from .models import MessageWhatsappTemplate

User = get_user_model()


class MessageWhatsappTemplateForm(forms.ModelForm):
    MESSAGE_TYPE_CHOICES = [
        ('reservation_created', 'Reservation Created (User)'),
        ('reservation_assigned_doctor', 'Assigned to Doctor'),
        ('reservation_assigned_technician', 'Assigned to Technician'),
    ]

    message_type = forms.ChoiceField(
        choices=MESSAGE_TYPE_CHOICES,
        widget=forms.Select(attrs={'class': 'form-select'})
    )

    class Meta:
        model = MessageWhatsappTemplate
        fields = ['message_type', 'content']
        widgets = {
            'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 10}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.pk:
            # جلوگیری از تغییر نوع پیام در حالت ویرایش
            self.fields['message_type'].disabled = True


class EmployeeRegistrationForm(forms.Form):
    first_name = forms.CharField(
        max_length=150,
        label='First Name',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter First Name'
        })
    )

    last_name = forms.CharField(
        max_length=150,
        label='Last Name',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Last Name'
        })
    )

    email = forms.EmailField(
        label='Email',
        required=False,
        widget=forms.EmailInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter Email'
        })
    )

    access_level = forms.ChoiceField(
        choices=AccessLevel.CHOICES,
        label='User Role',
        widget=forms.Select(attrs={
            'class': 'form-control',
            'id': 'id_access_level'
        })
    )

    country_code = forms.CharField(
        widget=forms.HiddenInput(attrs={
            'class': 'form-control',
            'id': 'id_country_code'
        }),
        required=False
    )

    phone_number = forms.CharField(
        label='Phone Number',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'ex: 9121234455',
            'id': 'id_phone_number'
        })
    )

    selected_person = forms.CharField(
        required=False,
        widget=forms.HiddenInput()
    )

    def clean_first_name(self):
        first_name = self.cleaned_data.get('first_name')
        if not first_name or not first_name.strip():
            raise forms.ValidationError('First name is required.')
        return first_name.strip()

    def clean_last_name(self):
        last_name = self.cleaned_data.get('last_name')
        if not last_name or not last_name.strip():
            raise forms.ValidationError('Last name is required.')
        return last_name.strip()

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get('phone_number')
        if not phone_number or not phone_number.strip():
            raise forms.ValidationError('Phone number is required.')
        return phone_number.strip()

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise forms.ValidationError('This email is already in use.')
        return email


class PasswordResetForm(forms.Form):
    username = forms.CharField(
        max_length=150,
        label='username',
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'enter username '
        })
    )

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if not User.objects.filter(username=username).exists():
            raise forms.ValidationError('No user found with that username.')
        return username




class UserRegisterForm(forms.ModelForm):
    first_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('First name')}), 
        max_length=150,
        required=True
    )
    last_name = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('Last name')}), 
        max_length=150,
        required=True
    )
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _('Username')}), 
        max_length=150, 
        required=False
    )
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': _('Email')}), 
        required=False
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': _('Password')}), 
        min_length=8, 
        required=False  # Make it optional
    )
    confirm_password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': _('Confirm Password')}), 
        required=False  # Make it optional
    )
    access_level = forms.ChoiceField(
        choices=AccessLevel.CHOICES, 
        widget=forms.Select(attrs={"class": "form-select"}), 
        required=True
    )

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'access_level']

    def __init__(self, *args, **kwargs):
        # If instance is provided (editing an existing user), set the password fields as optional
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.fields['password'].required = False
            self.fields['confirm_password'].required = False

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")

        # Password matching check only if both are provided
        if password and confirm_password and password != confirm_password:
            raise ValidationError(_("Passwords do not match."))
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data.get("password")

        if password:
            user.set_password(password)
        if commit:
            user.save()
        return user


from django import forms
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from django.contrib.auth.forms import AuthenticationForm
User = get_user_model()


class UserLoginForm(AuthenticationForm):
    username = forms.CharField(
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Username',
            'autocomplete': 'username'
        })
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'class': 'form-control',
            'placeholder': 'Password',
            'id': 'loginPassword',
            'autocomplete': 'current-password'
        })
    )
    remember_me = forms.BooleanField(
        required=False,
        initial=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        label='Remember me'
    )

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username')
        password = cleaned_data.get('password')

        if username and password:
            user = User.objects.filter(username=username).first()

            if not user:
                raise ValidationError(_("Invalid username or password."))

            if not user.is_active:
                raise ValidationError(_("This account is inactive."))

            if not user.check_password(password):
                raise ValidationError(_("Invalid username or password."))

        return cleaned_data
