"""
Template tags for permission-aware navigation system
"""
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.urls import reverse, NoReverseMatch
from ..navigation_service import navigation_service
import logging

logger = logging.getLogger(__name__)
register = template.Library()


@register.inclusion_tag('components/navigation_menu.html', takes_context=True)
def render_navigation_menu(context, menu_type='sidebar'):
    """
    Render the navigation menu based on user permissions
    
    Args:
        menu_type: 'sidebar', 'mobile', or 'breadcrumb'
    """
    request = context['request']
    user = request.user
    
    if not user.is_authenticated:
        return {'navigation_items': {}, 'current_url': '', 'menu_type': menu_type}
    
    try:
        current_url = request.path
        navigation_items = navigation_service.get_navigation_for_user(user, current_url)
        
        return {
            'navigation_items': navigation_items,
            'current_url': current_url,
            'menu_type': menu_type,
            'user': user,
            'request': request
        }
    except Exception as e:
        logger.error(f"Error rendering navigation menu: {e}")
        return {'navigation_items': {}, 'current_url': '', 'menu_type': menu_type}


@register.inclusion_tag('components/breadcrumb_navigation.html', takes_context=True)
def render_breadcrumbs(context):
    """
    Render breadcrumb navigation
    """
    request = context['request']
    user = request.user
    
    if not user.is_authenticated:
        return {'breadcrumbs': []}
    
    try:
        current_url = request.path
        breadcrumbs = navigation_service.get_breadcrumbs(user, current_url)
        
        return {
            'breadcrumbs': breadcrumbs,
            'current_url': current_url,
            'user': user
        }
    except Exception as e:
        logger.error(f"Error rendering breadcrumbs: {e}")
        return {'breadcrumbs': []}


@register.inclusion_tag('components/quick_actions.html', takes_context=True)
def render_quick_actions(context, limit=6):
    """
    Render quick action buttons based on user role and permissions
    """
    request = context['request']
    user = request.user
    
    if not user.is_authenticated:
        return {'quick_actions': []}
    
    try:
        quick_actions = navigation_service.get_quick_actions(user)[:limit]
        
        return {
            'quick_actions': quick_actions,
            'user': user,
            'request': request
        }
    except Exception as e:
        logger.error(f"Error rendering quick actions: {e}")
        return {'quick_actions': []}


@register.simple_tag(takes_context=True)
def has_navigation_access(context, permission_string):
    """
    Check if user has access to a specific navigation item
    
    Usage: {% has_navigation_access 'loans_create_application' as can_create_loans %}
    """
    user = context['request'].user
    
    if not user.is_authenticated:
        return False
    
    try:
        if hasattr(user, 'has_page_permission') and '_' in permission_string:
            page, action = permission_string.split('_', 1)
            return user.has_page_permission(page, action)
        else:
            return user.has_perm(permission_string)
    except Exception as e:
        logger.error(f"Error checking navigation access: {e}")
        return False


@register.simple_tag(takes_context=True)
def get_navigation_badge_count(context, badge_type):
    """
    Get badge count for navigation items (e.g., notification count)
    
    Usage: {% get_navigation_badge_count 'notifications' %}
    """
    user = context['request'].user
    
    if not user.is_authenticated:
        return 0
    
    try:
        # This would integrate with actual notification/task counting systems
        badge_counts = {
            'notifications': 0,  # Would get from notification system
            'pending_tasks': 0,  # Would get from task system
            'pending_approvals': 0,  # Would get from approval system
        }
        
        return badge_counts.get(badge_type, 0)
    except Exception as e:
        logger.error(f"Error getting badge count for {badge_type}: {e}")
        return 0


@register.filter
def is_current_page(current_url, item_url):
    """
    Check if the current URL matches the navigation item URL
    """
    try:
        return current_url == item_url or current_url.startswith(item_url.rstrip('/') + '/')
    except (AttributeError, TypeError):
        return False


@register.filter
def get_icon_class(icon_name):
    """
    Convert icon name to full CSS class
    """
    if not icon_name:
        return 'fas fa-circle'
    
    if icon_name.startswith('fa'):
        return icon_name
    else:
        return f'fas fa-{icon_name}'


@register.simple_tag
def navigation_tooltip(title, description=None, shortcut=None):
    """
    Generate tooltip content for navigation items
    
    Usage: {% navigation_tooltip "Dashboard" "View your personalized dashboard" "Ctrl+D" %}
    """
    tooltip_parts = [title]
    
    if description:
        tooltip_parts.append(description)
    
    if shortcut:
        tooltip_parts.append(f"Shortcut: {shortcut}")
    
    return " | ".join(tooltip_parts)


@register.inclusion_tag('components/navigation_search.html', takes_context=True)
def render_navigation_search(context):
    """
    Render navigation search component
    """
    request = context['request']
    user = request.user
    
    if not user.is_authenticated:
        return {'search_items': []}
    
    try:
        # Get all accessible navigation items for search
        navigation_items = navigation_service.get_navigation_for_user(user)
        search_items = []
        
        for category, items in navigation_items.items():
            for item in items:
                search_items.append({
                    'title': item.title,
                    'url': item.get_url(),
                    'icon': item.icon,
                    'category': category,
                    'description': item.description or item.tooltip
                })
                
                # Add children
                for child in item.children:
                    search_items.append({
                        'title': f"{item.title} > {child.title}",
                        'url': child.get_url(),
                        'icon': child.icon,
                        'category': category,
                        'description': child.description or child.tooltip
                    })
        
        return {
            'search_items': search_items,
            'user': user
        }
    except Exception as e:
        logger.error(f"Error rendering navigation search: {e}")
        return {'search_items': []}


@register.simple_tag(takes_context=True)
def get_contextual_help(context, page_name=None):
    """
    Get contextual help for the current page or specified page
    """
    request = context['request']
    user = request.user
    
    if not user.is_authenticated:
        return []
    
    try:
        # This would integrate with a help system
        # For now, return role-based help
        help_items = {
            'admin': [
                {
                    'title': 'Navigation Tips',
                    'content': 'Use the search function (Ctrl+K) to quickly find any page or feature.'
                },
                {
                    'title': 'Permission Management',
                    'content': 'Click on any staff member to manage their specific permissions.'
                }
            ],
            'team_leader': [
                {
                    'title': 'Team Overview',
                    'content': 'Your dashboard shows key metrics for your team performance.'
                },
                {
                    'title': 'Quick Actions',
                    'content': 'Use the quick action buttons to perform common tasks faster.'
                }
            ],
            'loan_officer': [
                {
                    'title': 'Client Management',
                    'content': 'Access your assigned clients quickly from the Portfolio section.'
                },
                {
                    'title': 'Loan Processing',
                    'content': 'Pending tasks are highlighted with badges in the navigation.'
                }
            ],
            'secretary': [
                {
                    'title': 'Document Management',
                    'content': 'Upload and organize client documents from the Documents section.'
                },
                {
                    'title': 'Client Registration',
                    'content': 'Use the quick action to add new clients efficiently.'
                }
            ],
            'auditor': [
                {
                    'title': 'Report Access',
                    'content': 'All compliance reports are available in the Reports section.'
                },
                {
                    'title': 'Data Export',
                    'content': 'Export functionality is available on most data views.'
                }
            ]
        }
        
        return help_items.get(user.role, [])
    except Exception as e:
        logger.error(f"Error getting contextual help: {e}")
        return []


@register.simple_tag
def navigation_keyboard_shortcuts():
    """
    Get keyboard shortcuts for navigation
    """
    return {
        'search': 'Ctrl+K',
        'dashboard': 'Ctrl+D',
        'clients': 'Ctrl+C',
        'loans': 'Ctrl+L',
        'reports': 'Ctrl+R',
        'settings': 'Ctrl+S',
        'help': 'F1'
    }