from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from .models import Brand
from .forms import BrandForm

class BrandListView(LoginRequiredMixin, View):
    def get(self, request):
        brands = Brand.objects.filter(trash=False).order_by('-created_at')
        return render(request, 'pages/brand-management/brand_list.html', {'brands': brands})

class BrandCreateView(LoginRequiredMixin, View):
    def get(self, request):
        form = BrandForm()
        return render(request, 'pages/brand-management/brand_form.html', {'form': form, 'title': 'Create Brand'})

    def post(self, request):
        form = BrandForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, 'Brand created successfully!')
            return redirect('brand-management')
        return render(request, 'pages/brand-management/brand_form.html', {'form': form, 'title': 'Create Brand'})

class BrandUpdateView(LoginRequiredMixin, View):
    def get(self, request, pk):
        brand = get_object_or_404(Brand, pk=pk)
        form = BrandForm(instance=brand)
        return render(request, 'pages/brand-management/brand_form.html', {'form': form, 'title': 'Edit Brand', 'brand': brand})

    def post(self, request, pk):
        brand = get_object_or_404(Brand, pk=pk)
        form = BrandForm(request.POST, request.FILES, instance=brand)
        if form.is_valid():
            form.save()
            messages.success(request, 'Brand updated successfully!')
            return redirect('brand-management')
        return render(request, 'pages/brand-management/brand_form.html', {'form': form, 'title': 'Edit Brand', 'brand': brand})

class BrandDeleteView(LoginRequiredMixin, View):
    def post(self, request, pk):
        brand = get_object_or_404(Brand, pk=pk)
        brand.trash = True
        brand.save()
        messages.success(request, 'Brand deleted successfully!')
        return redirect('brand-management')

