from django.contrib import admin
from .models import Ticket, Client, Portfolio, Activity, Document
import secrets
import string

@admin.register(Ticket)
class TicketAdmin(admin.ModelAdmin):
    list_display = ('subject', 'status', 'priority', 'requester_email', 'created_at')
    list_filter = ('status', 'priority')
    search_fields = ('subject', 'requester_email', 'description')

@admin.register(Client)
class ClientAdmin(admin.ModelAdmin):
    list_display = ('name', 'surname', 'email', 'phone', 'created_at')
    search_fields = ('name', 'surname', 'email')
    readonly_fields = ('generated_password',)
    fieldsets = (
        (None, {
            'fields': ('name', 'surname', 'email', 'phone', 'address', 'fiscal_code', 'vat_number')
        }),
        ('Credenziali', {
            'fields': ('generated_password',)
        }),
    )

    def save_model(self, request, obj, form, change):
        if not obj.pk:  # Only generate password for new clients
            alphabet = string.ascii_letters + string.digits
            password = ''.join(secrets.choice(alphabet) for i in range(12))
            obj.generated_password = password
        super().save_model(request, obj, form, change)

@admin.register(Portfolio)
class PortfolioAdmin(admin.ModelAdmin):
    list_display = ('name', 'client', 'created_at')
    search_fields = ('name', 'client__name', 'client__surname')
    list_filter = ('client',)

@admin.register(Activity)
class ActivityAdmin(admin.ModelAdmin):
    list_display = ('title', 'client', 'status', 'activity_date', 'created_at')
    search_fields = ('title', 'client__name', 'client__surname')
    list_filter = ('status', 'activity_date', 'client')

@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):
    list_display = ('title', 'client', 'created_at')
    search_fields = ('title', 'client__name', 'client__surname')
    list_filter = ('client',)
