from django import forms
from .models import RentalOwner, RentalListing, RentalInquiry, RentalOwnerBankingDetails

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import PasswordChangeForm
from common.choices import SRI_LANKA_CITY_CHOICES, SRI_LANKA_DISTRICT_CHOICES
from django.contrib.auth.forms import PasswordResetForm

User = get_user_model()

class RentalOwnerPasswordResetForm(PasswordResetForm):
    """
    Only allows password reset emails for active users
    who have a RentalOwnerProfile.
    """

    def get_users(self, email):
        active_users = super().get_users(email)
        for user in active_users:
            if hasattr(user, 'rental_owner_profile'):
                yield user


class RentalOwnerProfileForm(forms.ModelForm):
    class Meta:
        model = RentalOwner
        fields = [
            'owner_type',
            'full_name',
            'email',
            'whatsapp_number',
            'phone_number',
            'city',
            'address',
            'business_name',
        ]
        widgets = {
            'owner_type': forms.Select(attrs={'class': 'form-select'}),
            'full_name': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'whatsapp_number': forms.TextInput(attrs={'class': 'form-control'}),
            'phone_number': forms.TextInput(attrs={'class': 'form-control'}),
            'city': forms.Select(attrs={'class': 'form-select'}),
            'address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'business_name': forms.TextInput(attrs={'class': 'form-control'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].choices = [('', 'Select city')] + list(SRI_LANKA_CITY_CHOICES)


class RentalOwnerProfileImageForm(forms.ModelForm):
    class Meta:
        model = RentalOwner
        fields = ['profile_image']


class RentalOwnerUsernameChangeForm(forms.Form):
    username = forms.CharField(max_length=150, widget=forms.TextInput(attrs={'class': 'form-control'}))

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = user
        self.fields['username'].initial = user.username

    def clean_username(self):
        username = self.cleaned_data['username'].strip()
        if User.objects.exclude(pk=self.user.pk).filter(username=username).exists():
            raise forms.ValidationError("This username is already taken.")
        return username

    def save(self):
        self.user.username = self.cleaned_data['username']
        self.user.save(update_fields=['username'])
        return self.user


class StyledRentalOwnerPasswordChangeForm(PasswordChangeForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

class RentalOwnerSignupForm(forms.ModelForm):
    class Meta:
        model = RentalOwner
        fields = [
            'owner_type',
            'full_name',
            'email',
            'whatsapp_number',
            'phone_number',
            'city',
            'address',
            'business_name',
            'profile_image',
        ]
        widgets = {
            'owner_type': forms.Select(attrs={'class': 'form-select'}),
            'full_name': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
            'whatsapp_number': forms.TextInput(attrs={'class': 'form-control'}),
            'phone_number': forms.TextInput(attrs={'class': 'form-control'}),
            'city': forms.Select(attrs={'class': 'form-select'}),
            'address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'business_name': forms.TextInput(attrs={'class': 'form-control'}),
            'profile_image': forms.ClearableFileInput(attrs={'class': 'form-control'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].choices = [('', 'Select city')] + list(SRI_LANKA_CITY_CHOICES)



class RentalInquiryForm(forms.ModelForm):
    class Meta:
        model = RentalInquiry
        fields = ['full_name', 'email', 'whatsapp_number', 'message']
        widgets = {
            'full_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Your full name'}),
            'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Your email'}),
            'whatsapp_number': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'WhatsApp number'}),
            'message': forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'placeholder': 'Your message'}),
        }

class MultipleFileInput(forms.ClearableFileInput):
    allow_multiple_selected = True


class RentalListingForm(forms.ModelForm):
    class Meta:
        model = RentalListing
        fields = [
            'title',
            'property_type',
            'visibility',
            'city',
            'area',
            'address',
            'monthly_rent_usd',
            'security_deposit_usd',
            'bedrooms',
            'bathrooms',
            'max_occupants',
            'furnishing',
            'has_wifi',
            'has_ac',
            'has_kitchen',
            'has_parking',
            'near_beach',
            'suitable_for_remote_work',
            'short_description',
            'full_description',
            'house_rules',
            'available_from',
            'is_available',
        ]
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'property_type': forms.Select(attrs={'class': 'form-select'}),
            'visibility': forms.Select(attrs={'class': 'form-select'}),
            'city': forms.Select(attrs={'class': 'form-select'}),
            'area': forms.Select(attrs={'class': 'form-select'}),
            'address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'monthly_rent_usd': forms.NumberInput(attrs={'class': 'form-control'}),
            'security_deposit_usd': forms.NumberInput(attrs={'class': 'form-control'}),
            'bedrooms': forms.NumberInput(attrs={'class': 'form-control'}),
            'bathrooms': forms.NumberInput(attrs={'class': 'form-control'}),
            'max_occupants': forms.NumberInput(attrs={'class': 'form-control'}),
            'furnishing': forms.Select(attrs={'class': 'form-select'}),
            'has_wifi': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'has_ac': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'has_kitchen': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'has_parking': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'near_beach': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'suitable_for_remote_work': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'short_description': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
            'full_description': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'house_rules': forms.Textarea(attrs={'class': 'form-control', 'rows': 4}),
            'available_from': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'is_available': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].choices = [('', 'Select city')] + list(SRI_LANKA_CITY_CHOICES)
        self.fields['area'].choices = [('', 'Select district')] + list(SRI_LANKA_DISTRICT_CHOICES)


class RentalListingImageUploadForm(forms.Form):
    images = forms.FileField(
        required=False,
        widget=MultipleFileInput(attrs={
            'class': 'form-control',
            'accept': 'image/*',
        })
    )

class RentalOwnerBankingDetailsForm(forms.ModelForm):
    class Meta:
        model = RentalOwnerBankingDetails
        fields = [
            'account_holder_name',
            'bank_name',
            'branch_name',
            'account_number',
            'iban',
            'swift_code',
            'bank_country',
            'bank_address',
            'payment_notes',
        ]
        widgets = {
            'account_holder_name': forms.TextInput(attrs={'class': 'form-control'}),
            'bank_name': forms.TextInput(attrs={'class': 'form-control'}),
            'branch_name': forms.TextInput(attrs={'class': 'form-control'}),
            'account_number': forms.TextInput(attrs={'class': 'form-control'}),
            'iban': forms.TextInput(attrs={'class': 'form-control'}),
            'swift_code': forms.TextInput(attrs={'class': 'form-control'}),
            'bank_country': forms.TextInput(attrs={'class': 'form-control'}),
            'bank_address': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'payment_notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
        }