from django.contrib import admin
from django.urls import path
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.utils.translation import gettext_lazy as _
from .models import Profile, Truck, Shipment, Bid, Message, WhatsAppConfig, Country
from .whatsapp import send_whatsapp_message

@admin.register(Country)
class CountryAdmin(admin.ModelAdmin):
    list_display = ('name', 'code', 'is_default')
    list_editable = ('is_default',)

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'role', 'country_code', 'phone_number')
    list_filter = ('role',)
    search_fields = ('user__username', 'phone_number')

@admin.register(Truck)
class TruckAdmin(admin.ModelAdmin):
    list_display = ('truck_type', 'model', 'plate_no', 'owner', 'load_capacity')
    search_fields = ('plate_no', 'owner__username', 'truck_type')

@admin.register(Shipment)
class ShipmentAdmin(admin.ModelAdmin):
    list_display = ('origin', 'destination', 'shipper', 'status', 'delivery_date')
    list_filter = ('status', 'delivery_date')
    search_fields = ('origin', 'destination', 'shipper__username')

@admin.register(Bid)
class BidAdmin(admin.ModelAdmin):
    list_display = ('shipment', 'truck_owner', 'amount', 'status')
    list_filter = ('status',)
    search_fields = ('shipment__origin', 'shipment__destination', 'truck_owner__username')

@admin.register(Message)
class MessageAdmin(admin.ModelAdmin):
    list_display = ('shipment', 'sender', 'timestamp')
    search_fields = ('content', 'sender__username')

@admin.register(WhatsAppConfig)
class WhatsAppConfigAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'is_active')

    def has_add_permission(self, request):
        # Only allow one configuration record
        if self.model.objects.exists():
            return False
        return super().has_add_permission(request)

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('send-test/', self.admin_site.admin_view(self.send_test_message), name='send_test_whatsapp'),
        ]
        return custom_urls + urls

    def send_test_message(self, request):
        if request.method == 'POST':
            phone = request.POST.get('phone')
            message = request.POST.get('message')
            if phone and message:
                success = send_whatsapp_message(phone, message)
                if success:
                    self.message_user(request, _("Test message sent successfully!"))
                else:
                    self.message_user(request, _("Failed to send test message. Check your API credentials and logs."), level=messages.ERROR)
            return HttpResponseRedirect("../")
        
        context = dict(
           self.admin_site.each_context(request),
           title=_("Send Test WhatsApp Message"),
           opts=self.model._meta,
        )
        return render(request, "admin/core/whatsapp_test.html", context)