from django.contrib import admin
from django.shortcuts import redirect
from django.urls import reverse
from .models import ThawaniSettings, WablasSettings, PlatformProfile

class SingletonAdmin(admin.ModelAdmin):
    def changelist_view(self, request, extra_context=None):
        model = self.model
        if model.objects.exists():
            obj = model.objects.first()
            return redirect(reverse(f'admin:{model._meta.app_label}_{model._meta.model_name}_change', args=[obj.pk]))
        else:
            return redirect(reverse(f'admin:{model._meta.app_label}_{model._meta.model_name}_add'))

    def has_add_permission(self, request):
        if self.model.objects.exists():
            return False
        return super().has_add_permission(request)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['show_save_and_add_another'] = False
        # extra_context['show_save_and_continue'] = False # Optional: keep if user wants to save and stay
        return super().change_view(request, object_id, form_url, extra_context=extra_context)

    def add_view(self, request, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['show_save_and_add_another'] = False
        return super().add_view(request, form_url, extra_context=extra_context)

@admin.register(ThawaniSettings)
class ThawaniSettingsAdmin(SingletonAdmin):
    fieldsets = (
        ('API Credentials', {
            'fields': ('api_key', 'publishable_key'),
            'description': 'Enter your Thawani Pay API credentials.'
        }),
        ('Environment', {
            'fields': ('is_sandbox',),
            'description': 'Toggle Sandbox mode for testing.'
        }),
    )

@admin.register(WablasSettings)
class WablasSettingsAdmin(SingletonAdmin):
    fieldsets = (
        ('Connection Details', {
            'fields': ('api_url', 'api_token'),
            'description': 'Configuration for WhatsApp integration via Wablas.'
        }),
        ('Security', {
            'fields': ('secret_key',),
        }),
    )

@admin.register(PlatformProfile)
class PlatformProfileAdmin(SingletonAdmin):
    fieldsets = (
        ('Identity', {
            'fields': ('name', 'logo', 'description'),
            'classes': ('wide',),
        }),
        ('Contact Information', {
            'fields': ('contact_email', 'contact_phone', 'address'),
            'classes': ('wide',),
        }),
        ('Social Presence', {
            'fields': ('facebook_link', 'twitter_link', 'instagram_link'),
            'classes': ('collapse',),
        }),
    )