from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Product, Category, ProductImage, Discount

class CheckoutForm(forms.Form):
    """Contact Information - Now Optional"""
    address = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'form-control', 
            'rows': 3,
            'placeholder': 'Optional if using saved shipping address'
        }),
        required=False,           # ← This makes it optional
        label="Additional Address (Optional)"
    )
    
    phone = forms.CharField(
        max_length=15,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Phone number (Optional)'
        }),
        required=False,           # ← This makes it optional
        label="Contact Phone (Optional)"
    )
    


class ProductCreateForm(forms.ModelForm):
    new_category = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Create new category'})
    )

    class Meta:
        model = Product
        fields = ['name', 'category', 'description', 'price', 'stock', 'allow_customer_offer', 'min_offer_price']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 5, 'class': 'form-control'}),
            'price': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01'}),
            'stock': forms.NumberInput(attrs={'class': 'form-control'}),
            'allow_customer_offer': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'min_offer_price': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01'}),
        }

class OfferRequestForm(forms.Form):
    offered_price = forms.DecimalField(
        max_digits=12,
        decimal_places=2,
        min_value=0.01,
        widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter your offer price'
        }),
        label='Your Offer'
    )
    message = forms.CharField(
        widget=forms.Textarea(attrs={
            'class': 'form-control',
            'rows': 4,
            'placeholder': 'Optional message or details for the seller'
        }),
        required=False,
        label='Message (optional)'
    )

class ProductImageForm(forms.ModelForm):
    class Meta:
        model = ProductImage
        fields = ['product', 'image', 'alt_text', 'is_primary']
        widgets = {
            'product': forms.Select(attrs={'class': 'form-select'}),
            'image': forms.FileInput(attrs={'class': 'form-control'}),
            'alt_text': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Alt text (optional)'}),
            'is_primary': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }

class StockAdjustmentForm(forms.Form):
    new_stock = forms.IntegerField(min_value=0, label="New Stock Quantity")
    reason = forms.ChoiceField(choices=[
        ('restock', 'Restock from supplier'),
        ('sale_correction', 'Sale correction'),
        ('return', 'Customer return'),
        ('damage', 'Damaged/lost stock'),
        ('other', 'Other'),
    ])
    notes = forms.CharField(widget=forms.Textarea(attrs={'rows': 3}), required=False)


# ====================== DISCOUNT FORMS ======================
class DiscountCodeForm(forms.Form):
    """Simple form for applying a discount code at checkout"""
    code = forms.CharField(
        max_length=50,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Enter discount code',
            'autocomplete': 'off'
        }),
        label='Discount Code'
    )


class DiscountForm(forms.ModelForm):
    """Form for creating/editing discounts (admin only)"""
    
    class Meta:
        model = Discount
        fields = [
            'name', 'description', 'code', 'discount_type', 'discount_value',
            'min_purchase', 'products', 'categories', 'is_active',
            'start_date', 'end_date', 'usage_limit', 'usage_limit_per_user'
        ]
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'code': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'E.g., SAVE20, WELCOME10',
                'help_text': 'Leave empty for automatic discounts'
            }),
            'discount_type': forms.Select(attrs={'class': 'form-select'}),
            'discount_value': forms.NumberInput(attrs={
                'class': 'form-control',
                'step': '0.01',
                'placeholder': 'E.g., 20 for 20% or 5000 for $5000'
            }),
            'min_purchase': forms.NumberInput(attrs={
                'class': 'form-control',
                'step': '0.01',
                'placeholder': 'E.g., 50000'
            }),
            'products': forms.CheckboxSelectMultiple(attrs={'class': 'form-check'}),
            'categories': forms.CheckboxSelectMultiple(attrs={'class': 'form-check'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'start_date': forms.DateTimeInput(attrs={
                'class': 'form-control',
                'type': 'datetime-local'
            }),
            'end_date': forms.DateTimeInput(attrs={
                'class': 'form-control',
                'type': 'datetime-local'
            }),
            'usage_limit': forms.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': 'Leave empty for unlimited uses'
            }),
            'usage_limit_per_user': forms.NumberInput(attrs={
                'class': 'form-control',
                'placeholder': 'Leave empty for unlimited per user'
            }),
        }
    
    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get('start_date')
        end_date = cleaned_data.get('end_date')
        
        if start_date and end_date and start_date >= end_date:
            raise forms.ValidationError('Start date must be before end date.')
        
        discount_type = cleaned_data.get('discount_type')
        discount_value = cleaned_data.get('discount_value')
        
        if discount_type == 'percentage' and discount_value and discount_value > 100:
            raise forms.ValidationError('Percentage discount cannot exceed 100%.')
        
        return cleaned_data
    
    