from django.contrib import admin
from django.urls import path
from django.shortcuts import render
from django.utils.html import format_html
from django.http import HttpResponseRedirect
from .manager import PluginLoader
from pms_integration.models import PMSConfiguration, PMSIntegrationLog
from django import forms
from pms_integration.utils import get_all_plugins
from django.urls import reverse

class PMSConfigurationForm(forms.ModelForm):
    class Meta:
        model = PMSConfiguration
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        plugins = PluginLoader.load_plugins()
        plugin_choices = [(plugin_name, plugin_name) for plugin_name in plugins.keys()]
        self.fields['plugin_name'] = forms.ChoiceField(choices=plugin_choices, required=False)

@admin.register(PMSConfiguration)
class PMSConfigurationAdmin(admin.ModelAdmin):
    form = PMSConfigurationForm
    list_display = ('name', 'plugin_name', 'created_at', 'check_plugins_button')
    search_fields = ('name', 'plugin_name')
    ordering = ('-created_at',)

    def check_plugins_button(self, obj=None):
        """
        Возвращает кнопку для проверки плагинов.
        """
        url = reverse('admin:check-plugins')  # Генерируем URL с помощью reverse
        return format_html(
            '<a class="button" href="{}">Проверить плагины</a>',
            url
        )
    check_plugins_button.short_description = "Действия"

    def check_plugins_view(self, request, *args, **kwargs):
        """
        Custom admin view to check and display available plugins.
        """
        plugins = get_all_plugins()
        return render(request, "pms_integration/admin/check_plugins.html", {"plugins": plugins})

    def get_urls(self):
        """
        Add custom URLs to the admin panel.
        """
        urls = super().get_urls()
        custom_urls = [
            path("check-plugins/", self.admin_site.admin_view(self.check_plugins_view), name="check-plugins"),
        ]
        return custom_urls + urls
@admin.register(PMSIntegrationLog)
class PMSIntegrationLogAdmin(admin.ModelAdmin):
    list_display = ('hotel', 'checked_at', 'status', 'message')
    search_fields = ('hotel__name', 'status', 'message')
    list_filter = ('status', 'checked_at')
    ordering = ('-checked_at',)