"""
Role-Based Dashboard Views
Handles rendering of customized dashboards based on user roles and permissions
"""
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.core.cache import cache
from .dashboard_service import RoleBasedDashboardService, get_dashboard_context
from .decorators import permission_required
import logging

logger = logging.getLogger(__name__)


@login_required
def role_based_dashboard(request):
    """
    Main role-based dashboard view
    Renders different dashboard layouts based on user role and permissions
    """
    try:
        # Check cache first
        cache_key = f"dashboard_context_{request.user.id}_{request.user.role}"
        context = cache.get(cache_key)
        
        if not context:
            # Generate fresh context
            context = get_dashboard_context(request.user)
            # Cache for 5 minutes
            cache.set(cache_key, context, 300)
        
        # Add request-specific data
        context['request'] = request
        
        return render(request, 'users/role_based_dashboard.html', context)
        
    except Exception as e:
        logger.error(f"Error rendering dashboard for user {request.user.id}: {e}")
        messages.error(request, "Error loading dashboard. Please try again.")
        return redirect('users:profile', user_id=request.user.id)


@login_required
@require_http_methods(["GET"])
def dashboard_data_refresh(request):
    """
    AJAX endpoint to refresh dashboard data without full page reload
    """
    try:
        service = RoleBasedDashboardService(request.user)
        data = service.refresh_dashboard_data()
        
        return JsonResponse({
            'success': True,
            'data': data,
            'timestamp': timezone.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error refreshing dashboard data for user {request.user.id}: {e}")
        return JsonResponse({
            'success': False,
            'error': 'Failed to refresh dashboard data'
        }, status=500)


@method_decorator(login_required, name='dispatch')
class CustomizableDashboardView(TemplateView):
    """
    Advanced customizable dashboard view with widget management
    """
    template_name = 'users/customizable_dashboard.html'
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        try:
            # Get base dashboard context
            dashboard_context = get_dashboard_context(self.request.user)
            context.update(dashboard_context)
            
            # Add customization options
            context['available_widgets'] = self.get_available_widgets()
            context['user_widget_preferences'] = self.get_user_widget_preferences()
            
            return context
            
        except Exception as e:
            logger.error(f"Error in CustomizableDashboardView for user {self.request.user.id}: {e}")
            context['error'] = "Error loading dashboard customization options"
            return context
    
    def get_available_widgets(self):
        """Get list of widgets available to the user based on their role and permissions"""
        user = self.request.user
        widgets = []
        
        # Base widgets available to all users
        base_widgets = [
            {
                'id': 'profile_summary',
                'name': 'Profile Summary',
                'description': 'Your profile information and status',
                'category': 'personal',
                'permission_required': None
            },
            {
                'id': 'recent_activity',
                'name': 'Recent Activity',
                'description': 'Your recent system activities',
                'category': 'activity',
                'permission_required': 'dashboard_view_activity'
            },
            {
                'id': 'notifications',
                'name': 'Notifications',
                'description': 'System notifications and alerts',
                'category': 'communication',
                'permission_required': 'dashboard_view_notifications'
            }
        ]
        
        # Role-specific widgets
        role_widgets = {
            'admin': [
                {
                    'id': 'system_overview',
                    'name': 'System Overview',
                    'description': 'System-wide statistics and metrics',
                    'category': 'system',
                    'permission_required': 'dashboard_view_system_stats'
                },
                {
                    'id': 'user_management',
                    'name': 'User Management',
                    'description': 'Quick user management actions',
                    'category': 'management',
                    'permission_required': 'users_manage_staff'
                },
                {
                    'id': 'permission_overview',
                    'name': 'Permission Overview',
                    'description': 'Permission and role management summary',
                    'category': 'security',
                    'permission_required': 'users_manage_permissions'
                }
            ],
            'team_leader': [
                {
                    'id': 'team_performance',
                    'name': 'Team Performance',
                    'description': 'Team performance metrics and KPIs',
                    'category': 'performance',
                    'permission_required': 'team_view_performance'
                },
                {
                    'id': 'portfolio_overview',
                    'name': 'Portfolio Overview',
                    'description': 'Portfolio management and analytics',
                    'category': 'portfolio',
                    'permission_required': 'portfolio_view_analytics'
                }
            ],
            'loan_officer': [
                {
                    'id': 'my_portfolio',
                    'name': 'My Portfolio',
                    'description': 'Your assigned clients and loans',
                    'category': 'portfolio',
                    'permission_required': 'clients_view_assigned'
                },
                {
                    'id': 'pending_tasks',
                    'name': 'Pending Tasks',
                    'description': 'Tasks requiring your attention',
                    'category': 'tasks',
                    'permission_required': 'loans_view_pending'
                }
            ],
            'secretary': [
                {
                    'id': 'document_management',
                    'name': 'Document Management',
                    'description': 'Document processing and management',
                    'category': 'documents',
                    'permission_required': 'documents_manage_documents'
                },
                {
                    'id': 'client_communication',
                    'name': 'Client Communication',
                    'description': 'Client messages and communication',
                    'category': 'communication',
                    'permission_required': 'communication_manage_messages'
                }
            ],
            'auditor': [
                {
                    'id': 'audit_overview',
                    'name': 'Audit Overview',
                    'description': 'Audit status and compliance metrics',
                    'category': 'audit',
                    'permission_required': 'audit_view_dashboard'
                },
                {
                    'id': 'compliance_reports',
                    'name': 'Compliance Reports',
                    'description': 'Compliance reporting and analysis',
                    'category': 'compliance',
                    'permission_required': 'reports_view_compliance'
                }
            ]
        }
        
        # Add base widgets
        widgets.extend(base_widgets)
        
        # Add role-specific widgets
        if user.role in role_widgets:
            widgets.extend(role_widgets[user.role])
        
        # Filter widgets based on permissions
        available_widgets = []
        for widget in widgets:
            if widget['permission_required'] is None:
                available_widgets.append(widget)
            else:
                # Check if user has the required permission
                page, action = widget['permission_required'].split('_', 1)
                if hasattr(user, 'has_page_permission') and user.has_page_permission(page, action):
                    available_widgets.append(widget)
        
        return available_widgets
    
    def get_user_widget_preferences(self):
        """Get user's widget preferences from database or cache"""
        try:
            # This would typically load from a UserDashboardPreference model
            # For now, return default preferences
            return {
                'enabled_widgets': ['profile_summary', 'recent_activity', 'notifications'],
                'widget_order': ['profile_summary', 'recent_activity', 'notifications'],
                'layout': 'grid',  # or 'list'
                'refresh_interval': 300  # 5 minutes
            }
        except Exception as e:
            logger.error(f"Error loading user widget preferences: {e}")
            return {}


@login_required
@require_http_methods(["POST"])
def save_dashboard_preferences(request):
    """
    Save user's dashboard customization preferences
    """
    try:
        import json
        
        preferences = json.loads(request.body)
        
        # Validate preferences
        if not isinstance(preferences, dict):
            return JsonResponse({'success': False, 'error': 'Invalid preferences format'})
        
        # Save preferences (this would typically save to database)
        # For now, we'll use cache
        cache_key = f"dashboard_preferences_{request.user.id}"
        cache.set(cache_key, preferences, 86400)  # 24 hours
        
        # Invalidate dashboard context cache
        dashboard_cache_key = f"dashboard_context_{request.user.id}_{request.user.role}"
        cache.delete(dashboard_cache_key)
        
        return JsonResponse({
            'success': True,
            'message': 'Dashboard preferences saved successfully'
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'error': 'Invalid JSON format'
        }, status=400)
    except Exception as e:
        logger.error(f"Error saving dashboard preferences for user {request.user.id}: {e}")
        return JsonResponse({
            'success': False,
            'error': 'Failed to save preferences'
        }, status=500)


@login_required
@permission_required('dashboard', 'view_analytics')
def dashboard_analytics(request):
    """
    Dashboard analytics view for users with analytics permissions
    """
    try:
        context = {
            'user': request.user,
            'analytics_data': get_dashboard_analytics(request.user),
            'time_range': request.GET.get('range', '30d')
        }
        
        return render(request, 'users/dashboard_analytics.html', context)
        
    except Exception as e:
        logger.error(f"Error loading dashboard analytics for user {request.user.id}: {e}")
        messages.error(request, "Error loading analytics data.")
        return redirect('users:role_based_dashboard')


def get_dashboard_analytics(user):
    """
    Get dashboard analytics data for the user
    """
    try:
        from django.utils import timezone
        from datetime import timedelta
        
        # This would calculate actual analytics
        # For now, return sample data
        return {
            'login_frequency': {
                'daily_average': 2.5,
                'weekly_total': 18,
                'trend': 'up'
            },
            'feature_usage': {
                'most_used': 'Client Management',
                'least_used': 'Reports',
                'usage_distribution': {
                    'clients': 35,
                    'loans': 28,
                    'reports': 15,
                    'settings': 12,
                    'other': 10
                }
            },
            'performance_metrics': {
                'tasks_completed': 45,
                'average_response_time': '2.3 hours',
                'efficiency_score': 87
            }
        }
        
    except Exception as e:
        logger.error(f"Error calculating dashboard analytics: {e}")
        return {}


@login_required
def widget_data(request, widget_id):
    """
    Get data for a specific dashboard widget
    Used for AJAX loading of widget content
    """
    try:
        service = RoleBasedDashboardService(request.user)
        
        # Widget data handlers
        widget_handlers = {
            'system_overview': lambda: service.get_admin_context().get('system_stats', {}),
            'team_performance': lambda: service.get_team_leader_context().get('team_stats', {}),
            'my_portfolio': lambda: service.get_loan_officer_context().get('my_portfolio', {}),
            'document_management': lambda: service.get_secretary_context().get('document_stats', {}),
            'audit_overview': lambda: service.get_auditor_context().get('audit_stats', {}),
            'recent_activity': lambda: service.get_recent_activities(),
            'notifications': lambda: service.get_notifications(),
        }
        
        if widget_id in widget_handlers:
            data = widget_handlers[widget_id]()
            return JsonResponse({
                'success': True,
                'widget_id': widget_id,
                'data': data
            })
        else:
            return JsonResponse({
                'success': False,
                'error': f'Unknown widget: {widget_id}'
            }, status=404)
            
    except Exception as e:
        logger.error(f"Error loading widget data for {widget_id}: {e}")
        return JsonResponse({
            'success': False,
            'error': 'Failed to load widget data'
        }, status=500)