# forms.py
from django import forms
from decimal import Decimal
from .models import Donation, Project, ContactMessage, UserLogin, tb_actualitenews, dashboardpicture, tb_teams, tb_eventpostupdate, tb_eventcate, todolist
from django.core.validators import MinValueValidator, MaxValueValidator

class DonationForm(forms.ModelForm):
    class Meta:
        model = Donation
        fields = ['amount', 'payment_method', 'donator_name', 'donator_mail', 'donator_tel']
        widgets = {
            'payment_method': forms.RadioSelect(choices=[
                ('paypal', 'PayPal'),
                ('stripe', 'Stripe'),
                # ('flutterwave', 'Flutterwave'),
                ('cinetpay', 'CinetPay'),
            ])
        }
    
    def __init__(self, *args, **kwargs):
        self.project = kwargs.pop('project', None)
        super().__init__(*args, **kwargs)
        if self.project:
            self.fields['amount'].validators.append(MaxValueValidator(float(self.project.remaining_amount)))  # Removed parentheses
    
    def clean_amount(self):
        amount = self.cleaned_data['amount']
        if not isinstance(amount, Decimal):
            try:
                amount = Decimal(str(amount))
            except (ValueError, TypeError):
                raise forms.ValidationError("Invalid amount format")

        if self.project and amount > self.project.remaining_amount:  # Removed parentheses
            raise forms.ValidationError(
                f"Amount exceeds remaining project need. Maximum allowed: {self.project.remaining_amount}")  # Removed parentheses
        return amount
    
class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = [
            'title', 'description', 'target_amount', 
            'project_type', 'featured_image', 'is_active'
        ]
        widgets = {
            'description': forms.Textarea(attrs={'rows': 4}),
        }

class ContactForm(forms.ModelForm):
    class Meta:
        model = ContactMessage
        fields = ['name', 'email', 'subject', 'message']


class ActualiteNewsForm(forms.Form):  
    name = forms.CharField(
        required=True,
        max_length=2550,
        label='User Name',
        widget=forms.TextInput(attrs={'style': 'height: 30px;', 'class': 'form-control'})
    )
    
    title = forms.CharField(
        required=True,
        max_length=2550,
        label='News Title',
        widget=forms.TextInput(attrs={'style': 'height: 30px;', 'class': 'form-control'})
    )
    
    shortdes = forms.CharField(
        required=True,
        max_length=2500,
        label='Short Description',
        widget=forms.Textarea(attrs={
            'rows': 4,
            'style': 'width: 400px;',
            'class': 'form-control'
        })
    )
    
    longdes = forms.CharField(
        required=False,
        max_length=2500,
        label='Long Description',
        widget=forms.Textarea(attrs={
            'rows': 4,
            'style': 'width: 400px;',
            'class': 'form-control'
        })
    )
    
    status = forms.BooleanField(
        required=False,
        label='New Publication',
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )

    # Validation for word limit
    def clean_shortdes(self):
        return self._check_word_limit('shortdes', 2500)

    def clean_longdes(self):
        return self._check_word_limit('longdes', 2500)

    def _check_word_limit(self, field_name, limit):
        text = self.cleaned_data.get(field_name, "")
        word_count = len(text.split())
        if word_count > limit:
            raise forms.ValidationError(f"{field_name} cannot exceed {limit} words (currently {word_count} words).")
        return text



class DashImageForm(forms.ModelForm):

   class Meta:
    model = dashboardpicture
    fields = ['textdisplay1', 'textdisplay2', 'textdisplay3', 'picture']
    labels = {'textdisplay1':'Paragraph 1',  'textdisplay2':'Paragrah 2', 'textdisplay3':'Paragraph 3', 'picture':'Display Image'}
    

class EventspostForm(forms.ModelForm):

    textdisplay1 = forms.CharField(
    widget=forms.HiddenInput(),
    required=False
    )
    textdisplay2 = forms.CharField(
    widget=forms.HiddenInput(),
    required=False
    )
    textdisplay3 = forms.CharField(
    widget=forms.HiddenInput(),
    required=False
    )

    class Meta:
        model = tb_eventpostupdate
        fields = [
            'reportername', 'category', 'projectname', 'title', 'date',
            'textdisplay1', 'textdisplay2', 'textdisplay3',
            'displaypic', 'picture1', 'picture2', 'picture3', 'picture4', 'picture5'
        ]
        labels = {
            'reportername': '',
            'category': '',
            'projectname': '',
            'title': '',
            'date': '',
            'textdisplay1': '',
            'textdisplay2': '',
            'textdisplay3': '',
            'displaypic': '',
            'picture1': '',
            'picture2': '',
            'picture3': '',
            'picture4': '',
            'picture5': '',
        }
        widgets = {
            'date': forms.DateInput(attrs={'type': 'date'}),
        }

        title = forms.CharField(required=True,max_length=2550,label='News Title',widget=forms.TextInput(attrs={'style': 'height: 30px;', 'class': 'form-control'}))

    def clean_textdisplay1(self):
        return self._check_word_limit('textdisplay1')

    def clean_textdisplay2(self):
        return self._check_word_limit('textdisplay2')

    def clean_textdisplay3(self):
        return self._check_word_limit('textdisplay3')

    def _check_word_limit(self, field_name):
        text = self.cleaned_data.get(field_name, "")
        word_count = len(text.split())
        if word_count > 3000:
            raise forms.ValidationError(f"{field_name} cannot exceed 3000 words (currently {word_count} words).")
        return text
    

class LoginForm(forms.Form):
    userid = forms.CharField(max_length=50)
    password = forms.CharField(widget=forms.PasswordInput)

class teamupForm(forms.ModelForm):

    class Meta:
        model = tb_teams
        fields = [
            'position', 'department', 'staffname', 'staffsurname', 'staffmiddlename',
            'dob', 'address', 'region', 'office', 'datejoin',
            'textdisplay1', 'textdisplay2', 'textdisplay3', 'textdisplay4', 'textdisplay5',
            'dp', 'picture1', 'picture2', 'picture3'
        ]
        labels = {
            'position': '',
            'department': '',
            'staffname': '',
            'staffsurname': '',
            'staffmiddlename': '',
            'dob': '',
            'address': '',
            'region': '',
            'office': '',
            'datejoin': '',
            'textdisplay1': '',
            'textdisplay2': '',
            'textdisplay3': '',
            'textdisplay4': '',
            'textdisplay5': '',
            'dp': '',
            'picture1': '',
            'picture2': '',
            'picture3': '',
        }
        widgets = {
            'dob': forms.DateInput(attrs={'type': 'date'}),
            'datejoin': forms.DateInput(attrs={'type': 'date'}),
            'textdisplay1': forms.Textarea(attrs={
                'rows': 4, 'style': 'width: 400px;', 'class': 'form-control'
            }),
            'textdisplay2': forms.Textarea(attrs={
                'rows': 4, 'style': 'width: 400px;', 'class': 'form-control'
            }),
            'textdisplay3': forms.Textarea(attrs={
                'rows': 4, 'style': 'width: 400px;', 'class': 'form-control'
            }),
            'textdisplay4': forms.Textarea(attrs={
                'rows': 4, 'style': 'width: 400px;', 'class': 'form-control'
            }),
            'textdisplay5': forms.Textarea(attrs={
                'rows': 4, 'style': 'width: 400px;', 'class': 'form-control'
            }),
        }

    def clean_textdisplay1(self):
        return self._check_word_limit('textdisplay1')

    def clean_textdisplay2(self):
        return self._check_word_limit('textdisplay2')

    def clean_textdisplay3(self):
        return self._check_word_limit('textdisplay3')

    def clean_textdisplay4(self):
        return self._check_word_limit('textdisplay4')

    def clean_textdisplay5(self):
        return self._check_word_limit('textdisplay5')

    def _check_word_limit(self, field_name):
        text = self.cleaned_data.get(field_name, "")
        word_count = len(text.split())
        if word_count > 3000:
            raise forms.ValidationError(f"{field_name} cannot exceed 3000 words (currently {word_count} words).")
        return text
    
class popupForm(forms.ModelForm):

   class Meta:
    model = dashboardpicture
    fields = ['textdisplay1', 'textdisplay2', 'picture']
    labels = {'textdisplay1':'Name of Updater',  'textdisplay2':'Title', 'picture':'Display Image'}

class eventcateForm(forms.ModelForm):

   class Meta:
    model = tb_eventcate
    fields = ['name', 'description','title', 'picture']
    labels = {'name':'Name of Category',  'description':'Description','title':'Title', 'picture':'Category Image'}


class createadForm(forms.ModelForm):

   class Meta:
    model = UserLogin
    fields = ['userid', 'password','name', 'surname','dateofbirth','id_number', 'role']
    labels = {'name':'',  'surname':'','password':'', 'userid':'', 'dateofbirth':'', 'id_number':'', 'role':''}
    widgets = {
            'dob': forms.DateInput(attrs={'type': 'date'}),
            'dateofbirth': forms.DateInput(attrs={'type': 'date'}),
            'password':forms.PasswordInput(attrs={'type': 'password'})
        }
    
class editadminForm(forms.ModelForm):

   class Meta:
    model = UserLogin
    exclude = ['role']
    fields = ['userid', 'password','name', 'surname','dateofbirth','id_number']
    labels = {'name':'',  'surname':'','password':'', 'userid':'', 'dateofbirth':'', 'id_number':''}
    widgets = {
            'dob': forms.DateInput(attrs={'type': 'date'}),
            'dateofbirth': forms.DateInput(attrs={'type': 'date'}), 
            'password':forms.PasswordInput(attrs={'type': 'password'})
        }
    
class todoForm(forms.ModelForm):

   class Meta:
    model = todolist
    fields = ['taskname', 'inchargeperson','duedate', 'priority', 'status', 'adminid']
    labels = {'taskname':'',  'inchargeperson':'','duedate':''}
    widgets = {
            'duedate': forms.DateInput(attrs={'type': 'date'}),
        }