from django import forms
from .models import WardrobeItem, Accessory, Outfit, Category, OutfitFolder

class WardrobeItemForm(forms.ModelForm):
    main_category = forms.ModelChoiceField(
        queryset=Category.objects.filter(item_type='wardrobe', parent=None),
        required=False,
        empty_label="Select Main Category",
        widget=forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary', 'id': 'id_main_category'})
    )
    new_main_category = forms.CharField(
        max_length=100, required=False, label="Or add new main category",
        widget=forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'New main category...'})
    )
    new_subcategory = forms.CharField(
        max_length=100, required=False, label="Or add new subcategory",
        widget=forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'New subcategory...'})
    )
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.none()
        self.fields['category'].required = False
        self.fields['category'].label = "Subcategory"
        self.fields['name'].required = False

        if 'main_category' in self.data:
            try:
                main_category_id = int(self.data.get('main_category'))
                self.fields['category'].queryset = Category.objects.filter(parent_id=main_category_id).order_by('name')
            except (ValueError, TypeError):
                pass
        elif self.instance.pk and self.instance.category and self.instance.category.parent:
            self.fields['main_category'].initial = self.instance.category.parent
            self.fields['category'].queryset = Category.objects.filter(parent=self.instance.category.parent).order_by('name')

    class Meta:
        model = WardrobeItem
        fields = ['name', 'category', 'season', 'image']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'Item name (optional)...'}),
            'category': forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary', 'id': 'id_subcategory'}),
            'season': forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary'}),
            'image': forms.FileInput(attrs={'class': 'form-control bg-dark text-white border-secondary'}),
        }

    def save(self, commit=True):
        instance = super().save(commit=False)
        new_main = self.cleaned_data.get('new_main_category')
        new_sub = self.cleaned_data.get('new_subcategory')
        main_cat = self.cleaned_data.get('main_category')
        
        if new_main:
            parent_cat, _ = Category.objects.get_or_create(name=new_main, item_type='wardrobe', parent=None)
            if new_sub:
                child_cat, _ = Category.objects.get_or_create(name=new_sub, item_type='wardrobe', parent=parent_cat)
                instance.category = child_cat
            else:
                instance.category = parent_cat
        elif main_cat:
            if new_sub:
                child_cat, _ = Category.objects.get_or_create(name=new_sub, item_type='wardrobe', parent=main_cat)
                instance.category = child_cat
            # else category field itself handles it if selected
        
        if commit:
            instance.save()
        return instance

class AccessoryForm(forms.ModelForm):
    main_category = forms.ModelChoiceField(
        queryset=Category.objects.filter(item_type='accessory', parent=None),
        required=False,
        empty_label="Select Main Category",
        widget=forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary', 'id': 'id_main_category'})
    )
    new_main_category = forms.CharField(
        max_length=100, required=False, label="Or add new main category",
        widget=forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'New main category...'})
    )
    new_subcategory = forms.CharField(
        max_length=100, required=False, label="Or add new subcategory",
        widget=forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'New subcategory...'})
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category'].queryset = Category.objects.none()
        self.fields['category'].required = False
        self.fields['category'].label = "Subcategory"
        self.fields['name'].required = False

        if 'main_category' in self.data:
            try:
                main_category_id = int(self.data.get('main_category'))
                self.fields['category'].queryset = Category.objects.filter(parent_id=main_category_id).order_by('name')
            except (ValueError, TypeError):
                pass
        elif self.instance.pk and self.instance.category and self.instance.category.parent:
            self.fields['main_category'].initial = self.instance.category.parent
            self.fields['category'].queryset = Category.objects.filter(parent=self.instance.category.parent).order_by('name')

    class Meta:
        model = Accessory
        fields = ['name', 'category', 'season', 'image']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'Accessory name (optional)...'}),
            'category': forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary', 'id': 'id_subcategory'}),
            'season': forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary'}),
            'image': forms.FileInput(attrs={'class': 'form-control bg-dark text-white border-secondary'}),
        }

    def save(self, commit=True):
        instance = super().save(commit=False)
        new_main = self.cleaned_data.get('new_main_category')
        new_sub = self.cleaned_data.get('new_subcategory')
        main_cat = self.cleaned_data.get('main_category')
        
        if new_main:
            parent_cat, _ = Category.objects.get_or_create(name=new_main, item_type='accessory', parent=None)
            if new_sub:
                child_cat, _ = Category.objects.get_or_create(name=new_sub, item_type='accessory', parent=parent_cat)
                instance.category = child_cat
            else:
                instance.category = parent_cat
        elif main_cat:
            if new_sub:
                child_cat, _ = Category.objects.get_or_create(name=new_sub, item_type='accessory', parent=main_cat)
                instance.category = child_cat
        
        if commit:
            instance.save()
        return instance

class OutfitForm(forms.ModelForm):
    new_folder = forms.CharField(max_length=100, required=False, label="Or add new folder/group",
                                widget=forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'Enter new group name...'}))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].required = False
        self.fields['season'].required = False
        self.fields['items'].required = False
        self.fields['accessories'].required = False

    class Meta:
        model = Outfit
        fields = ['name', 'season', 'items', 'accessories', 'folder']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control bg-dark text-white border-secondary', 'placeholder': 'Outfit name (optional)...'}),
            'season': forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary'}),
            'items': forms.SelectMultiple(attrs={'class': 'form-select d-none'}), 
            'accessories': forms.SelectMultiple(attrs={'class': 'form-select d-none'}), 
            'folder': forms.Select(attrs={'class': 'form-select bg-dark text-white border-secondary'}),
        }

    def save(self, commit=True):
        instance = super().save(commit=False)
        new_folder_name = self.cleaned_data.get('new_folder')
        if new_folder_name:
            folder, _ = OutfitFolder.objects.get_or_create(name=new_folder_name)
            instance.folder = folder
        if commit:
            instance.save()
            self.save_m2m() 
        return instance