from django.contrib import admin, messages
from django.urls import path
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from .models import Channel, Tariff, SkylinkIPTVPlan,IPTVActivationLog
from .utils import fetch_and_update_channels,fetch_and_update_tariffs  
from django.utils.safestring import mark_safe
from django.forms import Textarea
from django.db import models
from django.utils.html import format_html
import json

@admin.register(Channel)
class ChannelAdmin(admin.ModelAdmin):
    list_display = ('id', 'channel_id', 'name', 'order', 'link', 'price')
    search_fields = ('name', 'channel_id', 'order', 'link')  # ✅ enables search on these fields
    change_list_template = "iptv_activation/admin/channel_change_list.html"  # custom template

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('update-channels/', self.admin_site.admin_view(self.update_channels), name='update-channels')
        ]
        return custom_urls + urls

    def update_channels(self, request):
        success, msg = fetch_and_update_channels()
        level = messages.SUCCESS if success else messages.ERROR
        self.message_user(request, msg, level=level)
        return redirect("..")
    
@admin.register(Tariff)
class TariffAdmin(admin.ModelAdmin):
    list_display = ('id', 'tariffs_id', 'name')
    search_fields= ('tariffs_id', 'name')
    change_list_template = "iptv_activation/admin/tariff_change_list.html"  # Custom template for adding button
    
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('update-tariffs/', self.admin_site.admin_view(self.update_tariffs), name='update-tariffs')
        ]
        return custom_urls + urls

    def update_tariffs(self, request):
        success, msg = fetch_and_update_tariffs()
        level = messages.SUCCESS if success else messages.ERROR
        self.message_user(request, msg, level=level)
        return redirect("..")

@admin.register(SkylinkIPTVPlan)
class SkylinkIPTVPlanAdmin(admin.ModelAdmin):
    list_display = ('name', 'code', 'status', 'amount', 'bandwidth_verified_flag')
    search_fields = ('name', 'code')
    list_filter = ('status', 'bandwidth_verified_flag')
    filter_horizontal = ('tariffs',)  # Enables multi-select box for many-to-many field

@admin.register(IPTVActivationLog)
class IPTVActivationLogAdmin(admin.ModelAdmin):
    list_display = (
        'id',
        'client_id',
        'phone_number',
        'activation_date',
        'status',
        'short_message',
    )
    list_filter = ('status', 'activation_date')
    search_fields = ('client_id', 'phone_number', 'message')

    readonly_fields = ('activation_date','formatted_input', 'formatted_output', )

    formfield_overrides = {
        models.JSONField: {'widget': Textarea(attrs={'rows': 20, 'cols': 120})},
    }

    def short_message(self, obj):
        return obj.message[:50] + "..." if obj.message else ""
    short_message.short_description = "Message"

    def view_on_site(self, obj):
        return None  # Optional: disables the "View on site" button

    def formatted_output(self, obj):
        try:
            formatted = json.dumps(obj.output, indent=2, ensure_ascii=False)
            return format_html('<pre style="white-space: pre-wrap;">{}</pre>', formatted)
        except Exception:
            return 'Invalid or Empty JSON'
    formatted_output.short_description = "Formatted Output"

    def formatted_input(self, obj):
        try:
            formatted = json.dumps(obj.input, indent=2, ensure_ascii=False)
            return format_html('<pre style="white-space: pre-wrap;">{}</pre>', formatted)
        except Exception:
            return 'Invalid or Empty JSON'
    formatted_input.short_description = "Formatted Input"