from django.contrib import admin
from django.utils import timezone
from .models import SlotTemplate, AppointmentSlot, Appointment
from .services import generate_slots_for_weeks


@admin.register(SlotTemplate)
class SlotTemplateAdmin(admin.ModelAdmin):
    list_display = ["weekday", "start_time", "end_time", "slot_duration_minutes", "is_online", "is_active", "updated_at"]
    list_filter = ["weekday", "is_online", "is_active"]
    search_fields = ["location_notes"]


@admin.register(AppointmentSlot)
class AppointmentSlotAdmin(admin.ModelAdmin):
    list_display = ["date", "start_time", "end_time", "is_online", "is_available_display", "created_at"]
    list_filter = ["date", "is_online"]
    search_fields = ["location_notes"]
    date_hierarchy = "date"
    readonly_fields = ["created_at"]

    def is_available_display(self, obj):
        return "Oui" if obj.is_available else "Non"
    is_available_display.short_description = "Disponible"

    actions = ["generate_future_slots"]

    @admin.action(description="Générer créneaux (4 semaines)")
    def generate_future_slots(self, request, queryset):
        count = generate_slots_for_weeks(num_weeks=4)
        self.message_user(request, f"{count} créneau(x) créé(s).")


@admin.register(Appointment)
class AppointmentAdmin(admin.ModelAdmin):
    list_display = ["guest_email", "guest_name", "slot_date_display", "slot_time_display", "status", "created_at"]
    list_filter = ["status", "slot__date", "slot__is_online"]
    search_fields = ["guest_email", "guest_name"]
    date_hierarchy = "slot__date"
    readonly_fields = ["created_at", "updated_at", "email_sent_at", "confirmed_at"]
    raw_id_fields = ["slot", "user"]

    def slot_date_display(self, obj):
        return obj.slot.date
    slot_date_display.short_description = "Date"

    def slot_time_display(self, obj):
        return f"{obj.slot.start_time} - {obj.slot.end_time}"
    slot_time_display.short_description = "Heure"
