from django import forms
from .mixins import AddClassMixin
from django.forms.models import inlineformset_factory
from .models import (
    Dealer,
    # Branch,
    Vendor,
    Customer,
    Car,
    CarFinance,
    CustomCard,
    CarRegistration,
    CarColors,
    ExteriorColors,
    InteriorColors,
    SaleQuotation
)
from django.forms import ModelMultipleChoiceField
from django.utils.translation import gettext_lazy as _


# Dealer Form
class DealerForm(forms.ModelForm):
    class Meta:
        model = Dealer
        fields = ['name', 'arabic_name', 'crn', 'vrn', '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):

    class Meta:
        model = CarFinance
        exclude = ['car', 'profit_margin', 'vat_amount', 'total', 'vat_rate']


# 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']


class CarColorsForm(forms.ModelForm):
    class Meta:
        model = CarColors
        fields = ['exterior', 'interior']

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

            self.fields['exterior'].queryset = ExteriorColors.objects.all()
            self.fields['exterior'].widget = forms.RadioSelect(attrs={'class': 'form-check-input'})
            self.fields['exterior'].choices = [
                (color.id, f"{color.get_local_name}") for color in ExteriorColors.objects.all().order_by('-name')
            ]

            self.fields['interior'].queryset = InteriorColors.objects.all()
            self.fields['interior'].widget = forms.RadioSelect(attrs={'class': 'form-check-input'})
            self.fields['interior'].choices = [
                (color.id, f"{color.get_local_name}") for color in InteriorColors.objects.all().order_by('-name')
            ]

    def clean(self):
        cleaned_data = super().clean()
        exterior = cleaned_data.get("exterior")
        interior = cleaned_data.get("interior")

        if not exterior or not interior:
            raise forms.ValidationError(_("Both exterior and interior colors must be selected."))

        return cleaned_data


class QuotationForm(forms.ModelForm):
    cars = ModelMultipleChoiceField(
        queryset=Car.objects.none(),  # Default empty queryset
        widget=forms.CheckboxSelectMultiple,
        label="Select Cars"
    )

    class Meta:
        model = SaleQuotation
        fields = ['customer', 'cars', 'remarks']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['cars'].queryset = Car.objects.filter(
            finances__isnull=False
        ).distinct()
