from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils import timezone
from .models import (
    Leader, Position, Group, GroupLeader, Member, 
    Contribution, Disbursement, MemberProfile
)

# ==================== FORMS ZA VIONGOZI ====================

class LeaderRegistrationForm(forms.ModelForm):
    """Mwenyekiti anajisajili"""
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Weka nenosiri'}),
        label="Nenosiri"
    )
    password_confirm = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Rudia nenosiri'}),
        label="Rudia nenosiri"
    )
    
    class Meta:
        model = Leader
        fields = ['phone_number', 'full_name']
        widgets = {
            'phone_number': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '0712345678'}),
            'full_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Jina lako kamili'}),
        }
        labels = {
            'phone_number': 'Namba ya simu',
            'full_name': 'Jina kamili',
        }
    
    def clean_phone_number(self):
        phone = self.cleaned_data.get('phone_number')
        # Hakikisha namba ina tarakimu 10 au 13 (kwa +255)
        if phone:
            phone = phone.strip()
            if phone.startswith('0') and len(phone) == 10:
                pass
            elif phone.startswith('+255') and len(phone) == 13:
                pass
            else:
                raise forms.ValidationError("Namba ya simu iwe kama 0712345678 au +255712345678")
        if Leader.objects.filter(phone_number=phone).exists():
            raise forms.ValidationError("Namba hii tayari imesajiliwa")
        return phone
    
    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        password_confirm = cleaned_data.get('password_confirm')
        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError("Manenosiri hayalingani")
        return cleaned_data


class LeaderLoginForm(AuthenticationForm):
    """Kiongozi anaingia"""
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '0712345678'}),
        label="Namba ya simu"
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Nenosiri'}),
        label="Nenosiri"
    )


class AddLeaderForm(forms.Form):
    """Mwenyekiti anaongeza kiongozi mwingine"""
    phone_number = forms.CharField(
        max_length=13,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '0712345678'}),
        label="Namba ya simu ya kiongozi"
    )
    full_name = forms.CharField(
        max_length=200,
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Jina kamili (hiari)'}),
        label="Jina kamili"
    )
    position = forms.ModelChoiceField(
        queryset=Position.objects.filter(is_active=True),
        widget=forms.Select(attrs={'class': 'form-control'}),
        label="Cheo"
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Weka nenosiri la kiongozi'}),
        label="Nenosiri"
    )
    
    def __init__(self, *args, **kwargs):
        self.group = kwargs.pop('group', None)
        super().__init__(*args, **kwargs)
        # Hakuna logic ya kuunda vyeo hapa - tu display
        # Kama hakuna vyeo, onyesha ujumbe
        if self.fields['position'].queryset.count() == 0:
            self.fields['position'].choices = []
            self.fields['position'].widget.attrs['disabled'] = True
            self.fields['position'].help_text = "Hakuna vyeo vilivyopo. Wasiliana na msimamizi."
    
    def clean_phone_number(self):
        phone = self.cleaned_data.get('phone_number')
        if phone:
            phone = phone.strip()
            if not (phone.startswith('0') or phone.startswith('+')):
                raise forms.ValidationError("Namba iwe kama 0712345678 au +255712345678")
        return phone

# ==================== FORMS ZA KIKUNDI ====================

class GroupCreateForm(forms.ModelForm):
    """Mwenyekiti anaunda kikundi kipya"""
    class Meta:
        model = Group
        fields = ['name', 'm_koba_number', 'description']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'K.m. VICOBA Upendo'}),
            'm_koba_number': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Namba ya M-Koba ya kikundi'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': 'Maelezo mafupi ya kikundi'}),
        }
        labels = {
            'name': 'Jina la kikundi',
            'm_koba_number': 'Namba ya M-Koba',
            'description': 'Maelezo',
        }


# ==================== FORMS ZA WANACHAMA ====================

class MemberForm(forms.ModelForm):
    """Kuongeza au kuhariri mwanachama"""
    class Meta:
        model = Member
        fields = ['full_name', 'phone_number', 'secret_pin']
        widgets = {
            'full_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Jina kamili la mwanachama'}),
            'phone_number': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '0712345678'}),
            'secret_pin': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'K.m. 01, 12, 45'}),
        }
        labels = {
            'full_name': 'Jina kamili',
            'phone_number': 'Namba ya simu',
            'secret_pin': 'PIN ya siri (anayoijua yeye tu)',
        }
    
    def clean_phone_number(self):
        phone = self.cleaned_data.get('phone_number')
        if phone:
            phone = phone.strip()
        return phone
    
    def clean_secret_pin(self):
        pin = self.cleaned_data.get('secret_pin')
        if pin:
            pin = pin.strip()
            if not pin.isdigit():
                raise forms.ValidationError("PIN iwe na namba tu (k.m. 01, 12, 45)")
        return pin


class MemberQueryForm(forms.Form):
    """Mwanachama anaingia kuangalia taarifa zake"""
    phone_number = forms.CharField(
        max_length=13,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '0712345678'}),
        label="Namba yako ya simu"
    )
    secret_pin = forms.CharField(
        max_length=10,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'PIN yako (k.m. 01)'}),
        label="PIN yako"
    )
    
    def clean_phone_number(self):
        phone = self.cleaned_data.get('phone_number')
        if phone:
            phone = phone.strip()
        return phone

# ==================== FORMS ZA MICHANGO ====================

class ContributionForm(forms.ModelForm):
    """Kurekodi mchango - unaweza kugawa kwa miezi mingi"""
    
    period_from_month = forms.ChoiceField(
        choices=[(str(i), i) for i in range(1, 13)],
        widget=forms.Select(attrs={'class': 'form-control'}),
        label="Anza Mwezi"
    )
    period_from_year = forms.IntegerField(
        widget=forms.NumberInput(attrs={'class': 'form-control', 'min': '2020'}),
        label="Anza Mwaka"
    )
    period_to_month = forms.ChoiceField(
        choices=[(str(i), i) for i in range(1, 13)],
        widget=forms.Select(attrs={'class': 'form-control'}),
        label="Ishia Mwezi"
    )
    period_to_year = forms.IntegerField(
        widget=forms.NumberInput(attrs={'class': 'form-control', 'min': '2020'}),
        label="Ishia Mwaka"
    )
    
    class Meta:
        model = Contribution
        fields = ['member', 'amount', 'reference_number', 'payment_date', 'notes']
        widgets = {
            'member': forms.Select(attrs={'class': 'form-control'}),
            'amount': forms.NumberInput(attrs={
                'class': 'form-control', 
                'placeholder': 'Kiasi cha jumla (Tsh)',
                'step': '1000',
                'min': '1',
            }),
            'reference_number': forms.TextInput(attrs={
                'class': 'form-control', 
                'placeholder': 'Reference number'
            }),
            'payment_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
        }
    
    def __init__(self, *args, **kwargs):
        self.group = kwargs.pop('group', None)
        super().__init__(*args, **kwargs)
        
        from django.utils import timezone
        
        if self.group:
            self.fields['member'].queryset = self.group.members.filter(is_active=True)
        
        # HAPA - Weka default kuwa mwezi wa sasa
        now = timezone.now()
        current_month = now.month
        current_year = now.year
        
        self.fields['period_from_month'].initial = current_month
        self.fields['period_from_year'].initial = current_year
        self.fields['period_to_month'].initial = current_month
        self.fields['period_to_year'].initial = current_year
    
    def clean(self):
        cleaned_data = super().clean()
        amount = cleaned_data.get('amount')
        from_month = cleaned_data.get('period_from_month')
        from_year = cleaned_data.get('period_from_year')
        to_month = cleaned_data.get('period_to_month')
        to_year = cleaned_data.get('period_to_year')
        
        if amount and from_month and from_year and to_month and to_year:
            try:
                from_month = int(from_month)
                from_year = int(from_year)
                to_month = int(to_month)
                to_year = int(to_year)
            except (TypeError, ValueError):
                raise forms.ValidationError("Tafadhali hakikisha mwezi na mwaka ni sahihi")
            
            months_count = (to_year - from_year) * 12 + (to_month - from_month) + 1
            
            if months_count <= 0:
                raise forms.ValidationError("Tarehe ya mwisho lazima iwe baada ya tarehe ya mwanzo")
            
            monthly_amount = amount / months_count
            
            if monthly_amount < 1000:
                raise forms.ValidationError(
                    f"Kiasi cha mwezi (Tsh {monthly_amount:,.0f}) ni kidogo sana."
                )
            
            cleaned_data['_months_count'] = months_count
            cleaned_data['_monthly_amount'] = monthly_amount
        
        return cleaned_data

class EditContributionForm(forms.ModelForm):
    """Kuhariri mchango uliopo - pamoja na kurekebisha mgawanyo wa miezi"""
    
    period_from_month = forms.ChoiceField(
        choices=[(str(i), i) for i in range(1, 13)],
        widget=forms.Select(attrs={'class': 'form-control'}),
        label="Anza Mwezi"
    )
    period_from_year = forms.IntegerField(
        widget=forms.NumberInput(attrs={'class': 'form-control', 'min': '2020'}),
        label="Anza Mwaka"
    )
    period_to_month = forms.ChoiceField(
        choices=[(str(i), i) for i in range(1, 13)],
        widget=forms.Select(attrs={'class': 'form-control'}),
        label="Ishia Mwezi"
    )
    period_to_year = forms.IntegerField(
        widget=forms.NumberInput(attrs={'class': 'form-control', 'min': '2020'}),
        label="Ishia Mwaka"
    )
    
    class Meta:
        model = Contribution
        fields = ['amount', 'reference_number', 'payment_date', 'notes']
        widgets = {
            'amount': forms.NumberInput(attrs={
                'class': 'form-control', 
                'placeholder': 'Kiasi cha jumla (Tsh)',
                'step': '1000',
                'min': '1',
            }),
            'reference_number': forms.TextInput(attrs={
                'class': 'form-control', 
                'placeholder': 'Reference number'
            }),
            'payment_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
        }
        labels = {
            'amount': 'Kiasi (Tsh)',
            'reference_number': 'Reference number',
            'payment_date': 'Tarehe ya malipo',
            'notes': 'Maelezo',
        }
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        from django.utils import timezone
        
        # Get allocations to determine period
        allocations = self.instance.allocations.all().order_by('year', 'month')
        
        if allocations.exists():
            # Kuna allocations - tumia kuanzia mwezi wa kwanza hadi wa mwisho
            first = allocations.first()
            last = allocations.last()
            self.fields['period_from_month'].initial = first.month
            self.fields['period_from_year'].initial = first.year
            self.fields['period_to_month'].initial = last.month
            self.fields['period_to_year'].initial = last.year
        else:
            # Hakuna allocations - tumia payment_month/year au default
            now = timezone.now()
            
            # Angalia kama fields zipo kwenye instance
            if hasattr(self.instance, 'payment_month') and self.instance.payment_month:
                self.fields['period_from_month'].initial = self.instance.payment_month
                self.fields['period_to_month'].initial = self.instance.payment_month
            else:
                self.fields['period_from_month'].initial = now.month
                self.fields['period_to_month'].initial = now.month
            
            if hasattr(self.instance, 'payment_year') and self.instance.payment_year:
                self.fields['period_from_year'].initial = self.instance.payment_year
                self.fields['period_to_year'].initial = self.instance.payment_year
            else:
                self.fields['period_from_year'].initial = now.year
                self.fields['period_to_year'].initial = now.year
        
        # Reference number na payment_date zinajaza automatically
        # Hakuna haja ya kuweka initial kwa maana form inazichukua kutoka instance
        
        if self.instance and self.instance.reference_number and '-M' in self.instance.reference_number:
            self.fields['amount'].help_text = "⚠️ ONYO: Hii ni sehemu ya malipo ya miezi mingi."    
    
    
    def clean(self):
        cleaned_data = super().clean()
        amount = cleaned_data.get('amount')
        from_month = cleaned_data.get('period_from_month')
        from_year = cleaned_data.get('period_from_year')
        to_month = cleaned_data.get('period_to_month')
        to_year = cleaned_data.get('period_to_year')
        
        # SKIP validation if no period data (kwa zamani au wakati wa kuhifadhi)
        if not all([amount, from_month, from_year, to_month, to_year]):
            return cleaned_data
        
        try:
            from_month = int(from_month)
            from_year = int(from_year)
            to_month = int(to_month)
            to_year = int(to_year)
        except (TypeError, ValueError):
            return cleaned_data
        
        months_count = (to_year - from_year) * 12 + (to_month - from_month) + 1
        
        if months_count <= 0:
            raise forms.ValidationError("Tarehe ya mwisho lazima iwe baada ya tarehe ya mwanzo")
        
        monthly_amount = amount / months_count
        
        if monthly_amount < 1000:
            raise forms.ValidationError(f"Kiasi cha mwezi (Tsh {monthly_amount:,.0f}) ni kidogo sana.")
        
        cleaned_data['_months_count'] = months_count
        cleaned_data['_monthly_amount'] = monthly_amount
        
        return cleaned_data

# ==================== FORMS ZA MISAADA ====================

class DisbursementForm(forms.ModelForm):
    """Kutoa msaada kwa mwanachama mwenye shida"""
    # amount = forms.IntegerField(
    #         widget=forms.NumberInput(attrs={
    #             'class': 'form-control', 
    #             'placeholder': 'K.m. 1000000',
    #             'step': '1000',  # Inaruhusu kuongeza kwa hatua za 1000
    #         }),
    #         label="Kiasi (Tsh)",
    #         min_value=1
    #     )
    
    class Meta:
        model = Disbursement
        fields = ['recipient_name', 'recipient_phone', 'amount', 'reason', 'reason_description', 'attachment', 'notes']
        widgets = {
            'recipient_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Jina kamili la mpokeaji'}),
            'recipient_phone': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Namba ya simu ya mpokeaji (kama ipo)'}),
            'amount': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Kiasi cha pesa (Tsh)'}),
            'reason': forms.Select(attrs={'class': 'form-control'}),
            'reason_description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': 'Maelezo ya kina kuhusu sababu ya msaada huu'}),
            'attachment': forms.FileInput(attrs={'class': 'form-control'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 2, 'placeholder': 'Maelezo ya ziada (hiari)'}),
        }
        labels = {
            'recipient_name': 'Jina la mpokeaji',
            'recipient_phone': 'Namba ya simu ya mpokeaji',
            'amount': 'Kiasi (Tsh)',
            'reason': 'Sababu',
            'reason_description': 'Maelezo ya sababu',
            'attachment': 'Kiambatisho (hati, barua, picha)',
            'notes': 'Maelezo ya ziada',
        }
    
    def clean_amount(self):
        amount = self.cleaned_data.get('amount')
        if amount and amount <= 0:
            raise forms.ValidationError("Kiasi lazima kiwe zaidi ya 0")
        return amount


class EditDisbursementForm(forms.ModelForm):
    """Kuhariri msaada uliopo"""
    # amount = forms.IntegerField(
    #         widget=forms.NumberInput(attrs={
    #             'class': 'form-control', 
    #             'placeholder': 'K.m. 1000000',
    #             'step': '1000',  # Inaruhusu kuongeza kwa hatua za 1000
    #         }),
    #         label="Kiasi (Tsh)",
    #         min_value=1
    #     )
    
    class Meta:
        model = Disbursement
        fields = ['recipient_name', 'recipient_phone', 'amount', 'reason', 'reason_description', 'attachment', 'notes']
        widgets = {
            'recipient_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Jina kamili la mpokeaji'}),
            'recipient_phone': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Namba ya simu ya mpokeaji'}),
            'amount': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Kiasi cha pesa (Tsh)'}),
            'reason': forms.Select(attrs={'class': 'form-control'}),
            'reason_description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': 'Maelezo ya sababu'}),
            'attachment': forms.FileInput(attrs={'class': 'form-control'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 2, 'placeholder': 'Maelezo ya ziada'}),
        }
        labels = {
            'recipient_name': 'Jina la mpokeaji',
            'recipient_phone': 'Namba ya simu ya mpokeaji',
            'amount': 'Kiasi (Tsh)',
            'reason': 'Sababu',
            'reason_description': 'Maelezo ya sababu',
            'attachment': 'Kiambatisho (hati, barua, picha)',
            'notes': 'Maelezo ya ziada',
        }


# ==================== FORMS ZA KUBADILISHA PIN YA MWANACHAMA ====================

class MemberChangePinForm(forms.ModelForm):
    """Mwanachama anabadilisha PIN yake (kwa ombi kwa kiongozi)"""
    
    class Meta:
        model = Member
        fields = ['secret_pin']
        widgets = {
            'secret_pin': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'PIN mpya (k.m. 05)'}),
        }
        labels = {
            'secret_pin': 'PIN mpya',
        }
    
    def clean_secret_pin(self):
        pin = self.cleaned_data.get('secret_pin')
        if pin:
            pin = pin.strip()
            if not pin.isdigit():
                raise forms.ValidationError("PIN iwe na namba tu")
        return pin
        
class MemberProfileForm(forms.ModelForm):
    """Form ya mwanachama kujaza taarifa zake"""
    
    class Meta:
        model = MemberProfile
        exclude = ['member', 'group', 'filled_by']
        widgets = {
            'gender': forms.Select(attrs={'class': 'form-control'}),
            'date_of_birth': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'marital_status': forms.Select(attrs={'class': 'form-control'}),
            'number_of_children': forms.NumberInput(attrs={'class': 'form-control', 'min': '0'}),
            'spouse_phone': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '07xx xxx xxx'}),
            'emergency_phone': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '07xx xxx xxx'}),
            'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'mkewako@gmail.com'}),
            'physical_address': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
            'region': forms.TextInput(attrs={'class': 'form-control'}),
            'district': forms.TextInput(attrs={'class': 'form-control'}),
            'ward': forms.TextInput(attrs={'class': 'form-control'}),
            'education_level': forms.Select(attrs={'class': 'form-control'}),
            'profession': forms.TextInput(attrs={'class': 'form-control'}),
            'place_of_work': forms.TextInput(attrs={'class': 'form-control'}),
            'skills': forms.Textarea(attrs={'class': 'form-control', 'rows': 2, 'placeholder': 'K.m. Sheria, Uhasibu, Ufundi, Daktari'}),
            'can_help_with': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
            'business_name': forms.TextInput(attrs={'class': 'form-control'}),
            'business_type': forms.TextInput(attrs={'class': 'form-control'}),
            'business_products': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
            'business_location': forms.TextInput(attrs={'class': 'form-control'}),
            'hobbies': forms.Textarea(attrs={'class': 'form-control', 'rows': 2}),
            'bio': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'phone_privacy': forms.Select(attrs={'class': 'form-control'}),
            'address_privacy': forms.Select(attrs={'class': 'form-control'}),
            'business_privacy': forms.Select(attrs={'class': 'form-control'}),
        }
        labels = {
            'gender': 'Jinsia',
            'date_of_birth': 'Tarehe ya kuzaliwa',
            'marital_status': 'Hali ya ndoa',
            'number_of_children': 'Idadi ya watoto',
            'spouse_phone': 'Namba ya mwenzi',
            'emergency_phone': 'Namba ya dharura (Lazima)',
            'email': 'Barua pepe',
            'physical_address': 'Anuani ya makazi',
            'region': 'Mkoa',
            'district': 'Wilaya',
            'ward': 'Kata',
            'education_level': 'Kiwango cha elimu',
            'profession': 'Taaluma/Kazi yako',
            'place_of_work': 'Mahali pa kazi',
            'skills': 'Ujuzi wako',
            'can_help_with': 'Unaweza kusaidia wanachama wenzako kwa namna gani?',
            'business_name': 'Jina la biashara (kama una)',
            'business_type': 'Aina ya biashara',
            'business_products': 'Bidhaa au huduma unazozitoa',
            'business_location': 'Mahali pa biashara',
            'hobbies': 'Mambo unayopenda kufanya',
            'bio': 'Maelezo mafupi kukuhusu',
            'phone_privacy': 'Namba yangu ionekane kwa',
            'address_privacy': 'Anuani yangu ionekane kwa',
            'business_privacy': 'Taarifa za biashara zionekane kwa',
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Make emergency_phone required
        self.fields['emergency_phone'].required = True        
        
        
        