from django import forms
from django.utils.translation import gettext_lazy as _
from bazi.models import Person
from datetime import date

class NumberPowerForm(forms.ModelForm):
    """Form for NumberPower calculation using the Person model."""
    
    class Meta:
        model = Person
        fields = ['name', 'gender', 'birth_date', 'birth_time', 'twin_type', 'father_dob', 'mother_dob', 'notes']
        labels = {
            'birth_date': _('出生日期'),
            'birth_time': _('出生时间'),
            'twin_type': _('双胞胎选项'),
            'father_dob': _('父亲出生日期'),
            'mother_dob': _('母亲出生日期'),
            'notes': _('备注'),
        }
        help_texts = {
            'birth_date': _('按照阳历/公历填写'),
            'birth_time': _('如不确定可留空'),
            'father_dob': _('双大必填'),
            'mother_dob': _('双小必填'),
        }
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'gender': forms.Select(attrs={'class': 'form-control'}),
            'birth_date': forms.DateInput(attrs={'class': 'form-control datepicker', 'type': 'date'}),
            'birth_time': forms.TimeInput(attrs={'class': 'form-control timepicker', 'type': 'time'}),
            'twin_type': forms.Select(attrs={'class': 'form-control'}),
            'father_dob': forms.DateInput(attrs={
                'class': 'form-control datepicker', 
                'type': 'date',
            }),
            'mother_dob': forms.DateInput(attrs={
                'class': 'form-control datepicker', 
                'type': 'date',
            }),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Set required fields
        self.fields['birth_date'].required = True
        self.fields['gender'].required = True
        
        # Make parent DOB fields not required initially
        self.fields['father_dob'].required = False
        self.fields['mother_dob'].required = False
        
        # Customize the twin_type choices
        self.fields['twin_type'].choices = [
            (0, '正常'),
            (1, '双大'),
            (2, '双小'),
        ]
    
    def clean(self):
        """
        Custom validation to ensure parent DOB is provided for twin cases
        """
        cleaned_data = super().clean()
        twin_type = cleaned_data.get('twin_type')
        
        # Convert to integer if it's a string
        if isinstance(twin_type, str) and twin_type.isdigit():
            twin_type = int(twin_type)
            
        if twin_type == 1:  # Twin big
            if not cleaned_data.get('father_dob'):
                self.add_error('father_dob', _('双大需要填写父亲出生日期'))
        
        elif twin_type == 2:  # Twin small
            if not cleaned_data.get('mother_dob'):
                self.add_error('mother_dob', _('双小需要填写母亲出生日期'))
        
        return cleaned_data

# JavaScript to toggle visibility of parent DOB fields based on twin selection
# This would go in your template or a separate JS file
"""
<script>
document.addEventListener('DOMContentLoaded', function() {
    const twinSelect = document.getElementById('twin-select');
    const fatherDob = document.getElementById('father-dob');
    const motherDob = document.getElementById('mother-dob');
    
    twinSelect.addEventListener('change', function() {
        // Hide both by default
        fatherDob.parentElement.style.display = 'none';
        motherDob.parentElement.style.display = 'none';
        
        if (this.value === '1') {  // Twin big
            fatherDob.parentElement.style.display = 'block';
        } else if (this.value === '2') {  // Twin small
            motherDob.parentElement.style.display = 'block';
        }
    });
});
</script>
"""

class NumberPowerCalculateForm(forms.Form):
    """Form for performing calculations on existing Person records."""
    
    person = forms.ModelChoiceField(
        queryset=Person.objects.all(),
        label=_('选择人员'),
        widget=forms.Select(attrs={'class': 'form-control'})
    )
