from django.contrib import admin
from django.forms import RadioSelect
from .models import Feedback, QRcodeGenerate, FaceProfile,PredefinedQA, ChatLog, ChatCategory
from django.utils.html import format_html
import json
from django.urls import reverse
from django.template.loader import render_to_string
from django.urls import path
from django.http import HttpResponse
from import_export import resources
from import_export.admin import ImportExportModelAdmin

@admin.register(Feedback)
class FeedbackAdmin(admin.ModelAdmin):
    list_display = ['rating', 'comment', 'contact', 'submitted_at', 'referrer']
    search_fields = ['comment', 'contact']




@admin.register(QRcodeGenerate)
class QRcodeGenerateAdmin(admin.ModelAdmin):
    list_display = ('name', 'url', 'qr_code', 'module_drawer', 'eye_drawer')
    readonly_fields = ('qr_code',)

    fieldsets = (
        (None, {
            'fields': ('name', 'url')
        }),
        ('QR Code Customization', {
            'fields': ('qr_size', 'qr_color', 'qr_background', 'module_drawer', 'eye_drawer')
        }),
    )

    # Override specific fields to show as radio buttons
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        form.base_fields['module_drawer'].widget = RadioSelect(choices=QRcodeGenerate.MODULE_DRAWER_CHOICES)
        form.base_fields['eye_drawer'].widget = RadioSelect(choices=QRcodeGenerate.EYE_DRAWER_CHOICES)
        return form
  

    # Inline CSS via Media for better layout (no external file)
    class Media:
        js = ()
        css = {
            'all': (
                '''
                data:text/css,
                fieldset .radio {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 10px;
                }
                fieldset .radio label {
                    border: 1px solid #ccc;
                    padding: 8px 12px;
                    cursor: pointer;
                    border-radius: 6px;
                    text-align: center;
                    width: auto;
                    font-weight: 500;
                }
                fieldset .radio input {
                    margin-right: 6px;
                }
                '''
            )
        }


        
@admin.register(FaceProfile)
class FaceProfileAdmin(admin.ModelAdmin):
    list_display = ('name', 'phone_number', 'created_at')
    search_fields = ('name', 'phone_number')

# Create a resource class for import/export
# Create a resource class for import/export
class PredefinedQAResource(resources.ModelResource):
    class Meta:
        model = PredefinedQA
        import_id_fields = ('id',)  # Use 'id' to identify existing records
        fields = ('id', 'question', 'answer', 'category')
        skip_unchanged = True  # Skip unchanged records to optimize performance
        report_skipped = True  # Report skipped records

class ChatCategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'description')
    search_fields = ('name', 'description')



@admin.register(PredefinedQA)
class PredefinedQAAdmin(ImportExportModelAdmin):
    resource_class = PredefinedQAResource
    list_display = ('question', 'short_answer', 'edit_link', 'category')
    search_fields = ('question', 'answer', 'category__name')
    list_filter = ('category',)

    def short_answer(self, obj):
        return format_html(obj.answer[:50] + '...') if len(obj.answer) > 50 else format_html(obj.answer)
    short_answer.short_description = "Answer Preview"

    def edit_link(self, obj):
        return format_html(f'<a href="/admin/feedback/predefinedqa/{obj.id}/change/">Edit</a>')
    edit_link.short_description = "Edit"

    
@admin.register(ChatCategory)
class ChatCategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'description', 'parent_name', 'is_active')
    search_fields = ('name', 'description')
    
    # Display categories based on their parent-child relationship
    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        
        # Show only categories that don't have a parent (Main Categories)
        if request.GET.get('parent__isnull', None) == 'True':
            queryset = queryset.filter(parent__isnull=True)
        return queryset

    def parent_name(self, obj):
        return obj.parent.name if obj.parent else '—'
    parent_name.short_description = 'Parent Category'

    # Optional: Limit queryset based on `parent` to only show children of a selected category.
    def get_list_display(self, request):
        if request.GET.get('parent__isnull', None) == 'True':
            return ('name', 'description', 'is_active')
        return ('name', 'description', 'parent_name', 'is_active')

    # Override the list_filter to show only the 'is_active' filter and remove 'parent'
    list_filter = ('is_active',)



@admin.register(ChatLog)
class ChatLogAdmin(admin.ModelAdmin):
    list_display = ("user_name", "user_email", "user_phone", "timestamp", "view_conversation_link")

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path(
                "conversation/<int:pk>/",
                self.admin_site.admin_view(self.view_conversation_popup),
                name="chatlog_popup"
            ),
        ]
        return custom_urls + urls

    def view_conversation_link(self, obj):
        url = reverse("admin:chatlog_popup", args=[obj.pk])
        return format_html(
            '<a href="{}" onclick="return showChatPopup(this.href);">'
            '<span style="font-size: 18px;">👁️</span></a>',
            url
        )

    def view_conversation_popup(self, request, pk):
        obj = self.get_object(request, pk)
        try:
            conv = json.loads(obj.conversation)
        except Exception:
            conv = []

        html = render_to_string("feedback/admin/chatlog_popup.html", {"conversation": conv, "user": obj})
        return HttpResponse(html)

    view_conversation_link.short_description = "Conversation"

    class Media:
        js = ('js/show_chat_popup.js',)