from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.contrib.auth import get_user_model
from .models import (
    Service, StaffMember, Appointment, 
    AppointmentNote, BusinessHours
)
from .forms import BusinessHoursForm

User = get_user_model()


class ServiceAdmin(admin.ModelAdmin):
    list_display = ('name', 'duration', 'price', 'is_active', 'created_at')
    list_filter = ('is_active', 'created_at')
    list_filter = ('is_active',)
    search_fields = ('name', 'description')
    prepopulated_fields = {'description': ('name',)}
    
    def duration_minutes(self, obj):
        return f"{obj.duration.seconds // 60} minutes"
    duration_minutes.short_description = 'Duration'


class StaffMemberAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'is_active', 'services_list')
    list_filter = ('is_active', 'services')
    search_fields = ('user__username', 'user__first_name', 'user__last_name', 'bio')
    filter_horizontal = ('services',)
    
    def services_list(self, obj):
        return ", ".join([s.name for s in obj.services.all()])
    services_list.short_description = 'Services Offered'


class AppointmentNoteInline(admin.StackedInline):
    model = AppointmentNote
    extra = 1
    fields = ('content', 'author', 'created_at')
    readonly_fields = ('author', 'created_at')
    
    def save_model(self, request, obj, form, change):
        if not obj.author_id:
            obj.author = request.user
        super().save_model(request, obj, form, change)


class AppointmentAdmin(admin.ModelAdmin):
    list_display = ('client', 'service', 'staff_member', 'start_time', 'end_time', 'status', 'is_past_due')
    list_filter = ('status', 'service', 'staff_member', 'start_time')
    search_fields = ('client__username', 'client__first_name', 'client__last_name', 'notes')
    readonly_fields = ('created_at', 'updated_at')
    date_hierarchy = 'start_time'
    inlines = [AppointmentNoteInline]
    
    fieldsets = (
        ('Appointment Details', {
            'fields': ('client', 'service', 'staff_member', 'status')
        }),
        ('Scheduling', {
            'fields': ('start_time', 'end_time')
        }),
        ('Additional Information', {
            'fields': ('notes', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def is_past_due(self, obj):
        if obj.status in ['completed', 'cancelled', 'no_show']:
            return ''
        return obj.end_time < timezone.now()
    is_past_due.boolean = True
    is_past_due.short_description = 'Past Due'


class AppointmentNoteAdmin(admin.ModelAdmin):
    list_display = ('truncated_content', 'appointment', 'author', 'created_at')
    list_filter = ('created_at', 'author')
    search_fields = ('content', 'appointment__client__username')
    readonly_fields = ('author', 'created_at')
    
    def truncated_content(self, obj):
        return obj.content[:50] + '...' if len(obj.content) > 50 else obj.content
    truncated_content.short_description = 'Content'
    
    def save_model(self, request, obj, form, change):
        if not obj.author_id:
            obj.author = request.user
        super().save_model(request, obj, form, change)


class BusinessHoursAdmin(admin.ModelAdmin):
    list_display = ('day_of_week', 'formatted_hours', 'is_closed')
    list_editable = ('is_closed',)
    ordering = ('day_of_week',)
    
    def formatted_hours(self, obj):
        if obj.is_closed:
            return 'Closed'
        return f"{obj.open_time.strftime('%I:%M %p')} - {obj.close_time.strftime('%I:%M %p')}"
    formatted_hours.short_description = 'Business Hours'
    
    def has_add_permission(self, request):
        # Only allow adding if there are less than 7 days (one for each day of the week)
        return super().has_add_permission(request) and BusinessHours.objects.count() < 7


# Register models
admin.site.register(Service, ServiceAdmin)
admin.site.register(StaffMember, StaffMemberAdmin)
admin.site.register(Appointment, AppointmentAdmin)
admin.site.register(AppointmentNote, AppointmentNoteAdmin)
admin.site.register(BusinessHours, BusinessHoursAdmin)
