from django import forms
from .mixins import AddClassMixin
from .models import (
    Dealer,
    # Branch,
    Vendor,
    Customer,
    Car,
    CarFinance,
    CustomCard,
    CarRegistration,
    CarColors
)
from django.contrib.contenttypes.forms import generic_inlineformset_factory
from django.utils.translation import gettext_lazy as _


# Dealer Form
class DealerForm(forms.ModelForm):
    class Meta:
        model = Dealer
        fields = ['crn', 'vrn', 'arabic_name', 'name', 'phone_number', 'address', 'logo']


# Customer Form
class CustomerForm(forms.ModelForm, AddClassMixin):
    class Meta:
        model = Customer
        fields = [
            'first_name', 'middle_name', 'last_name', 'email',
            'national_id', 'phone_number', 'address'
        ]


class CarForm(forms.ModelForm, AddClassMixin, ):
    class Meta:
        model = Car
        fields = [
            'vin', 'id_car_make', 'id_car_model',
            'year', 'id_car_serie', 'id_car_trim',
            'stock_type', 'remarks', 'mileage', 'receiving_date', 'vendor'
        ]
        widgets = {
            'receiving_date': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
            'remarks': forms.Textarea(attrs={'rows': 2}),
        }

    def __init__(self, *args, **kwargs):
        dealer = kwargs.pop('dealer', None)
        super().__init__(*args, **kwargs)
        # if dealer:
        #     self.fields['branch'].queryset = Branch.objects.filter(dealer=dealer)

        if 'id_car_make' in self.fields:
            queryset = self.fields['id_car_make'].queryset
            self.fields['id_car_make'].choices = [
                (obj.id_car_make, obj.get_local_name()) for obj in queryset
            ]


class CarUpdateForm(forms.ModelForm, AddClassMixin):
    class Meta:
        model = Car
        fields = ['vendor', 'status', 'stock_type', 'mileage', 'receiving_date', 'remarks']

        widgets = {
            'receiving_date': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
            'remarks': forms.Textarea(attrs={'rows': 2}),
        }

    def __init__(self, *args, **kwargs):
        dealer = kwargs.pop('dealer', None)
        super().__init__(*args, **kwargs)

        # if dealer and 'branch' in self.fields:
        #     self.fields['branch'].queryset = Branch.objects.filter(dealer=dealer)
        #     self.fields['branch'].choices = [
        #         (branch.id, branch.get_local_name()) for branch in self.fields['branch'].queryset
        #     ]

        if 'vendor' in self.fields:
            queryset = self.fields['vendor'].queryset
            if queryset:
                self.fields['vendor'].choices = [
                    (vendor.id, vendor.get_local_name()) for vendor in queryset
                ]


class CarFinanceForm(AddClassMixin, forms.ModelForm):
    profit_margin_percentage = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        min_value=0,
        max_value=100,
        label="Profit Margin",
        required=True,
        widget=forms.NumberInput(attrs={'min': '0', 'max': '100', 'step': '0.01'})
    )
    vat_rate_percentage = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        min_value=0,
        max_value=100,
        label="Vat Rate",
        required=True,
        widget=forms.NumberInput(attrs={'min': '0', 'max': '100', 'step': '0.01'})
    )

    class Meta:
        model = CarFinance
        fields = ['cost_price']

    def __init__(self, *args, **kwargs):
        super(CarFinanceForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            # Convert profit_margin from decimal to percentage for initial display
            self.fields['profit_margin_percentage'].initial = self.instance.profit_margin * 100
            self.fields['vat_rate_percentage'].initial = self.instance.vat_rate * 100

    def clean_profit_margin_percentage(self):
        profit_margin_percentage = self.cleaned_data['profit_margin_percentage']
        if not (0 <= profit_margin_percentage <= 100):
            raise forms.ValidationError('Profit margin must be between 0 and 100.')
        return profit_margin_percentage

    def clean_vat_rate_percentage(self):
        vat_rate_percentage = self.cleaned_data['vat_rate_percentage']
        if not (0 <= vat_rate_percentage <= 100):
            raise forms.ValidationError('vat rate must be between 0 and 100.')
        return vat_rate_percentage

    def save(self, commit=True):
        instance = super(CarFinanceForm, self).save(commit=False)
        profit_margin_percentage = self.cleaned_data['profit_margin_percentage']
        vat_rate_percentage = self.cleaned_data['vat_rate_percentage']
        instance.profit_margin = profit_margin_percentage / 100
        instance.vat_rate = vat_rate_percentage / 100
        if commit:
            instance.save()
        return instance


# Custom Card Form
class CustomCardForm(forms.ModelForm):
    custom_date = forms.DateTimeField(
        widget=forms.DateInput(attrs={'type': 'date'}),
        label=_("Custom Date"),
    )

    class Meta:
        model = CustomCard
        fields = ['custom_number', 'custom_date']


# Car Registration Form
class CarRegistrationForm(forms.ModelForm):
    class Meta:
        model = CarRegistration
        fields = [
            'car', 'plate_number', 'text1', 'text2', 'text3', 'registration_date'
        ]


class VendorForm(forms.ModelForm):
    class Meta:
        model = Vendor
        exclude = ['dealer']
