from django.contrib import admin
from .models import Category, Product
from management.models import Supplier
from django.utils.html import format_html
from .templatetags.filters import rupiah 
from import_export import resources, fields
from import_export.admin import ImportExportModelAdmin
from django.http import HttpResponse
from openpyxl import Workbook
from django.contrib.auth.models import User, Group, Permission
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin
from django.contrib.admin import register
from unfold.admin import ModelAdmin
from unfold.forms import UserChangeForm, UserCreationForm, AdminPasswordChangeForm
from unfold.contrib.import_export.forms import ExportForm, ImportForm, SelectableFieldsExportForm
from import_export.widgets import ForeignKeyWidget
import logging
from django.core.exceptions import ValidationError
from decimal import Decimal
from django.utils.translation import gettext_lazy as _


logger = logging.getLogger(__name__)



# Register your models here.

admin.site.unregister(User)
admin.site.unregister(Group)

@register(User)
class UserAdmin(BaseUserAdmin, ModelAdmin):
    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = AdminPasswordChangeForm

    def get_form(self, request, obj=None, **kwargs):
        # Mendapatkan form default dari UserAdmin
        form = super().get_form(request, obj, **kwargs)
        
        # Filter permissions hanya untuk model tertentu
        allowed_models = ['user', 'group', 'category', 'product', 'employee', 'supplier', 'customer', 'transaction']  # Model yang diizinkan
        permissions = Permission.objects.filter(
            content_type__model__in=allowed_models
        ).select_related('content_type')

        # Format permission choices
        permission_choices = [
            (perm.id, f"{perm.content_type.model} | {perm.codename}")
            for perm in permissions
        ]

        # Modifikasi hanya field 'user_permissions'
        if 'user_permissions' in form.base_fields:
            form.base_fields['user_permissions'].choices = permission_choices
        return form

@register(Group)
class GroupAdmin(BaseGroupAdmin, ModelAdmin):
    class Media:
        css = {
            'all': ('admin/css/widgets.css',)
        }
    
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        
        # Filter permissions hanya untuk model tertentu
        allowed_models = ['user', 'group', 'category', 'product', 'employee', 'supplier', 'customer', 'transaction']  # Model yang diizinkan
        permissions = Permission.objects.filter(
            content_type__model__in=allowed_models
        ).select_related('content_type')

        # Format permission choices
        permission_choices = [
            (perm.id, f"{perm.content_type.model} | {perm.codename}")
            for perm in permissions
        ]
        
        form.base_fields['permissions'].choices = permission_choices  # Perubahan di sini
        return form




def download_template(modeladmin, request, queryset):
    # Membuat workbook baru
    print("Aksi download template dipanggil")
    wb = Workbook()
    ws = wb.active
    ws.title = "Template"
    
    # Menambahkan header ke template Excel (ganti sesuai dengan field model yang relevan)
    headers = ['Name', 'Description']  # Sesuaikan dengan field yang kamu inginkan
    ws.append(headers)
    
    # Menyediakan response untuk mengunduh file Excel
    response = HttpResponse(content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = 'attachment; filename=product_template.xlsx'
    
    # Menyimpan file Excel ke response
    wb.save(response)
    return response

download_template.short_description = "Unduh Template Excel"  # Nama aksi yang ditampilkan di admin

# Buat resource untuk model Product
class ProductResource(resources.ModelResource):
    category = fields.Field(
        column_name='category_id',
        attribute='category',
        widget=ForeignKeyWidget(Category, 'id')
    )
    
    supplier = fields.Field(
        column_name='supplier_id',
        attribute='supplier',
        widget=ForeignKeyWidget(Supplier, 'id')
    )

    def before_import_row(self, row, **kwargs):
        # Validasi product number
        if not row.get('product_number'):
            raise ValidationError('Product number is required')
            
        # Validasi qty
        try:
            qty = int(row.get('qty', 0))
            if qty < 0:
                raise ValidationError('Quantity cannot be negative')
        except ValueError:
            raise ValidationError('Quantity must be a number')
            
        # Validasi price
        try:
            price = Decimal(str(row.get('price', 0)))
            if price < 0:
                raise ValidationError('Price cannot be negative')
        except:
            raise ValidationError('Price must be a valid number')
            
        # Validasi category
        if not row.get('category_id'):
            raise ValidationError('Category ID is required')
            
        # Calculate total
        row['total'] = qty * price

    def before_import(self, dataset, using_transactions=True, dry_run=False, **kwargs):
        # Validasi header
        headers = ['product_number', 'name', 'unit', 'price', 'qty', 'total', 'description', 'category_id', 'supplier_id']
        if set(headers) - set(dataset.headers):
            raise ValidationError(f'Required columns are missing. Required: {headers}')
        
    class Meta:
        model = Product
        skip_unchanged = True
        report_skipped = True
        fields = ('product_number', 'name', 'unit', 'price', 'qty', 'total', 'description', 'category', 'supplier')
        export_order = fields
        import_id_fields = ['product_number']  # Field unik untuk menghindari duplikasi data

@admin.register(Category)
class CategoryAdmin(ModelAdmin, admin.ModelAdmin):
    list_display = ('name', 'description', 'updated_at')
    search_fields = ('name', 'description')
    list_per_page = 10
    site_icon = "material-icons/outlined/category"

@admin.register(Product)
class ProductAdmin(ModelAdmin, ImportExportModelAdmin):
    list_display = ('formatted_product_number','category', 'supplier', 'name', 'qty', 'unit', 'formatted_price', 'formatted_total', 'updated_at')
    search_fields = ('product_number', 'name', 'unit', 'category__name', 'supplier__name')
    list_filter = ('category', 'unit', 'supplier')
    list_per_page = 10
    resource_class = ProductResource
    import_form_class= ImportForm
    export_form_class= SelectableFieldsExportForm   
    #actions = [download_template]

    def has_import_permission(self, request):
        # Hanya mengizinkan impor jika user memiliki permission selain "view_product"
        return request.user.has_perm('app.add_product') or request.user.has_perm('app.change_product') or request.user.has_perm('app.delete_product')

    def has_export_permission(self, request):
        return request.user.has_perm('app.add_product') or request.user.has_perm('app.change_product') or request.user.has_perm('app.delete_product')
    
    def supplier(self, obj):
        return obj.supplier.name if obj.supplier else '-'  # Jika supplier tidak ada, tampilkan '-'
    
    def formatted_product_number(self, obj):
        return obj.product_number
    formatted_product_number.short_description = 'Product ID'

    # Metode untuk memformat harga menggunakan filter
    def formatted_price(self, obj):
        return format_html('<div style="text-align: right;">{}</div>', rupiah(obj.price))  # Memformat price dengan rupiah filter
    formatted_price.short_description = "Price"
    
    # Metode untuk memformat total menggunakan filter
    def formatted_total(self, obj):
        return format_html('<div style="text-align: right;">{}</div>', rupiah(obj.total))  # Memformat total dengan rupiah filter
    formatted_total.short_description = "Total"

    def save_model(self, request, obj, form, change):
        if change:
            # Jika ini adalah update
            old_obj = self.model.objects.get(pk=obj.pk)
            if obj.qty > old_obj.qty:
                # Jika stok bertambah, simpan informasi tambahan
                obj._stock_notes = f"Stock updated by admin: {request.user.username}"
        super().save_model(request, obj, form, change)