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 Material
from .forms import MaterialForm

class MaterialListView(LoginRequiredMixin, View):
    def get(self, request):
        materials = Material.objects.filter(trash=False).order_by('-created_at')
        return render(request, 'pages/material-management/material_list.html', {'materials': materials})

class MaterialCreateView(LoginRequiredMixin, View):
    def get(self, request):
        form = MaterialForm()
        return render(request, 'pages/material-management/material_form.html', {'form': form, 'title': 'Create Material'})

    def post(self, request):
        form = MaterialForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Material created successfully!')
            return redirect('material-management')
        return render(request, 'pages/material-management/material_form.html', {'form': form, 'title': 'Create Material'})

class MaterialUpdateView(LoginRequiredMixin, View):
    def get(self, request, pk):
        material = get_object_or_404(Material, pk=pk)
        form = MaterialForm(instance=material)
        return render(request, 'pages/material-management/material_form.html', {'form': form, 'title': 'Edit Material', 'material': material})

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

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

