from django import forms
from .models import Account, Expense, ExpenseCategory, OtherIncome, OwnerDraw


class AccountForm(forms.ModelForm):
    class Meta:
        model = Account
        fields = ['name', 'account_type', 'balance']
        help_texts = {
            'balance': 'Opening balance for this account.'
        }


class ExpenseCategoryForm(forms.ModelForm):
    class Meta:
        model = ExpenseCategory
        fields = ['name', 'description']


class ExpenseForm(forms.ModelForm):
    class Meta:
        model = Expense
        fields = ['category', 'account', 'amount', 'description', 'reference', 'date']
        widgets = {
            'date': forms.DateInput(attrs={'type': 'date'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['account'].queryset = Account.objects.filter(is_active=True)

    def clean(self):
        cleaned_data = super().clean()
        account = cleaned_data.get('account')
        amount = cleaned_data.get('amount')
        if account and amount:
            if account.balance < amount:
                raise forms.ValidationError(
                    f'Insufficient balance in {account.name}. '
                    f'Available: {account.balance}'
                )
        return cleaned_data


class OtherIncomeForm(forms.ModelForm):
    class Meta:
        model = OtherIncome
        fields = ['account', 'amount', 'description', 'reference', 'date']
        widgets = {
            'date': forms.DateInput(attrs={'type': 'date'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['account'].queryset = Account.objects.filter(is_active=True)


class OwnerDrawForm(forms.ModelForm):
    class Meta:
        model = OwnerDraw
        fields = ['account', 'amount', 'description', 'date']
        widgets = {
            'date': forms.DateInput(attrs={'type': 'date'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['account'].queryset = Account.objects.filter(is_active=True)

    def clean(self):
        cleaned_data = super().clean()
        account = cleaned_data.get('account')
        amount = cleaned_data.get('amount')
        if account and amount:
            if account.balance < amount:
                raise forms.ValidationError(
                    f'Insufficient balance in {account.name}. '
                    f'Available: {account.balance}'
                )
        return cleaned_data