"""Django Admin Configuration for Standalone Configurations

This module provides admin interfaces for standalone VPN and FTP configurations
that can be used independently of channels and then linked to zones.

Author: Senior Django Developer
Version: 1.0.0
"""

from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.db.models import Count

from apps.channels.models import (
    StandaloneVPNConfiguration, StandaloneFTPConfiguration,
    ZoneVPNConfiguration, ZoneFTPConfiguration,
    IPSecConfiguration, OpenVPNConfiguration, WireGuardConfiguration
)


class ZoneVPNConfigurationInline(admin.TabularInline):
    """Inline admin for Zone-VPN Configuration relationships."""
    model = ZoneVPNConfiguration
    extra = 0
    fields = ('zone', 'is_active', 'priority', 'created_at')
    readonly_fields = ('created_at',)
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('zone')


class ZoneFTPConfigurationInline(admin.TabularInline):
    """Inline admin for Zone-FTP Configuration relationships."""
    model = ZoneFTPConfiguration
    extra = 0
    fields = ('zone', 'is_active', 'priority', 'created_at')
    readonly_fields = ('created_at',)
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('zone')


@admin.register(StandaloneVPNConfiguration)
class StandaloneVPNConfigurationAdmin(admin.ModelAdmin):
    """Admin interface for Standalone VPN Configurations."""
    list_display = (
        'name', 'vpn_type', 'zone_count', 'is_active', 
        'connection_status', 'created_at'
    )
    list_filter = ('vpn_type', 'is_active', 'created_at')
    search_fields = ('name', 'description')
    ordering = ('name',)
    readonly_fields = ('id', 'created_at', 'updated_at')
    
    fieldsets = (
        (_('Basic Information'), {
            'fields': ('name', 'description', 'vpn_type')
        }),
        (_('Configuration'), {
            'fields': ('is_active',)
        }),
        (_('VPN Specific Settings'), {
            'fields': ('ipsec_config', 'openvpn_config', 'wireguard_config'),
            'description': 'Select the appropriate configuration based on VPN type'
        }),
        (_('Metadata'), {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    inlines = [ZoneVPNConfigurationInline]
    
    def zone_count(self, obj):
        """Display number of zones using this VPN configuration."""
        count = obj.zone_vpn_configs.filter(is_active=True).count()
        if count > 0:
            return format_html(
                '<span style="color: green;">{} zones</span>', count
            )
        return format_html('<span style="color: gray;">0 zones</span>')
    zone_count.short_description = 'Active Zones'
    
    def connection_status(self, obj):
        """Display VPN connection status."""
        if obj.is_active:
            # In a real implementation, you would check actual VPN status
            return format_html(
                '<span style="color: green; font-weight: bold;">●</span> Active'
            )
        return format_html(
            '<span style="color: red; font-weight: bold;">●</span> Inactive'
        )
    connection_status.short_description = 'Status'
    
    def get_queryset(self, request):
        return super().get_queryset(request).prefetch_related(
            'zone_vpn_configs__zone'
        )
    
    actions = ['activate_configurations', 'deactivate_configurations']
    
    def activate_configurations(self, request, queryset):
        """Activate selected VPN configurations."""
        updated = queryset.update(is_active=True)
        self.message_user(
            request,
            f'Successfully activated {updated} VPN configuration(s).'
        )
    activate_configurations.short_description = 'Activate selected VPN configurations'
    
    def deactivate_configurations(self, request, queryset):
        """Deactivate selected VPN configurations."""
        updated = queryset.update(is_active=False)
        self.message_user(
            request,
            f'Successfully deactivated {updated} VPN configuration(s).'
        )
    deactivate_configurations.short_description = 'Deactivate selected VPN configurations'


@admin.register(StandaloneFTPConfiguration)
class StandaloneFTPConfigurationAdmin(admin.ModelAdmin):
    """Admin interface for Standalone FTP Configurations."""
    list_display = (
        'name', 'host', 'port', 'username', 'zone_count', 
        'is_active', 'connection_status', 'created_at'
    )
    list_filter = ('is_active', 'port', 'passive_mode', 'created_at')
    search_fields = ('name', 'host', 'username', 'description')
    ordering = ('name',)
    readonly_fields = ('id', 'created_at', 'updated_at')
    
    fieldsets = (
        (_('Basic Information'), {
            'fields': ('name', 'description')
        }),
        (_('Connection Settings'), {
            'fields': ('host', 'port', 'username', 'password')
        }),
        (_('Advanced Settings'), {
            'fields': ('root_directory', 'passive_mode', 'is_active'),
            'classes': ('collapse',)
        }),
        (_('Metadata'), {
            'fields': ('id', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    inlines = [ZoneFTPConfigurationInline]
    
    def zone_count(self, obj):
        """Display number of zones using this FTP configuration."""
        count = obj.zone_ftp_configs.filter(is_active=True).count()
        if count > 0:
            return format_html(
                '<span style="color: green;">{} zones</span>', count
            )
        return format_html('<span style="color: gray;">0 zones</span>')
    zone_count.short_description = 'Active Zones'
    
    def connection_status(self, obj):
        """Display FTP connection status."""
        if obj.is_active:
            # In a real implementation, you would test FTP connectivity
            return format_html(
                '<span style="color: green; font-weight: bold;">●</span> Active'
            )
        return format_html(
            '<span style="color: red; font-weight: bold;">●</span> Inactive'
        )
    connection_status.short_description = 'Status'
    
    def get_queryset(self, request):
        return super().get_queryset(request).prefetch_related(
            'zone_ftp_configs__zone'
        )
    
    actions = ['test_connections', 'activate_configurations', 'deactivate_configurations']
    
    def test_connections(self, request, queryset):
        """Test FTP connections for selected configurations."""
        # This would trigger the Celery task to validate configurations
        from apps.channels.tasks import validate_standalone_configurations
        
        task = validate_standalone_configurations.delay()
        self.message_user(
            request,
            f'Connection test initiated for {queryset.count()} FTP configuration(s). '
            f'Task ID: {task.id}'
        )
    test_connections.short_description = 'Test FTP connections'
    
    def activate_configurations(self, request, queryset):
        """Activate selected FTP configurations."""
        updated = queryset.update(is_active=True)
        self.message_user(
            request,
            f'Successfully activated {updated} FTP configuration(s).'
        )
    activate_configurations.short_description = 'Activate selected FTP configurations'
    
    def deactivate_configurations(self, request, queryset):
        """Deactivate selected FTP configurations."""
        updated = queryset.update(is_active=False)
        self.message_user(
            request,
            f'Successfully deactivated {updated} FTP configuration(s).'
        )
    deactivate_configurations.short_description = 'Deactivate selected FTP configurations'


@admin.register(ZoneVPNConfiguration)
class ZoneVPNConfigurationAdmin(admin.ModelAdmin):
    """Admin interface for Zone-VPN Configuration relationships."""
    list_display = ('zone', 'vpn_configuration', 'is_active', 'priority', 'created_at')
    list_filter = ('is_active', 'priority', 'created_at')
    search_fields = ('zone__name', 'vpn_configuration__name')
    ordering = ('zone__name', 'priority')
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'zone', 'vpn_configuration'
        )


@admin.register(ZoneFTPConfiguration)
class ZoneFTPConfigurationAdmin(admin.ModelAdmin):
    """Admin interface for Zone-FTP Configuration relationships."""
    list_display = ('zone', 'ftp_configuration', 'is_active', 'priority', 'created_at')
    list_filter = ('is_active', 'priority', 'created_at')
    search_fields = ('zone__name', 'ftp_configuration__name')
    ordering = ('zone__name', 'priority')
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'zone', 'ftp_configuration'
        )