from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.db import transaction
from django.views.decorators.http import require_http_methods
import json

from .models import CustomUser, RolePermission, UserPermission
from .decorators import admin_required


@login_required
@admin_required
def enhanced_staff_permissions(request, user_id):
    """Enhanced permission management with page-specific permissions"""
    
    user = get_object_or_404(CustomUser, id=user_id)
    
    if user.role not in ['admin', 'team_leader', 'loan_officer', 'secretary']:
        messages.error(request, 'This user is not a staff member.')
        return redirect('users:admin_list')
    
    if request.method == 'POST':
        try:
            with transaction.atomic():
                # Clear existing custom permissions
                UserPermission.objects.filter(user=user).delete()
                
                # Process form data and create new permissions
                permissions_created = 0
                
                # Define the permission mapping based on our new structure
                permission_mappings = {
                    # Dashboard permissions
                    'dashboard_access': ('dashboard', 'access'),
                    'dashboard_overview_access': ('dashboard_overview', 'access'),
                    'dashboard_metrics_access': ('dashboard_metrics', 'access'),
                    'dashboard_charts_access': ('dashboard_charts', 'access'),
                    
                    # Clients permissions
                    'clients_access': ('clients', 'access'),
                    'clients_view_list_access': ('clients_view_list', 'access'),
                    'clients_create_new_create': ('clients_create_new', 'create'),
                    'clients_edit_profile_edit': ('clients_edit_profile', 'edit'),
                    'clients_delete_client_delete': ('clients_delete_client', 'delete'),
                    'clients_view_details_access': ('clients_view_details', 'access'),
                    'clients_loan_history_access': ('clients_loan_history', 'access'),
                    'clients_payment_history_access': ('clients_payment_history', 'access'),
                    'clients_kyc_documents_access': ('clients_kyc_documents', 'access'),
                    'clients_assign_portfolio_assign': ('clients_assign_portfolio', 'assign'),
                    'clients_registration_fee_manage': ('clients_registration_fee', 'manage'),
                    'clients_status_change_edit': ('clients_status_change', 'edit'),
                    'clients_export_data_export': ('clients_export_data', 'export'),
                    
                    # Loans permissions
                    'loans_access': ('loans', 'access'),
                    'loans_view_list_access': ('loans_view_list', 'access'),
                    'loans_create_application_create': ('loans_create_application', 'create'),
                    'loans_edit_application_edit': ('loans_edit_application', 'edit'),
                    'loans_delete_loan_delete': ('loans_delete_loan', 'delete'),
                    'loans_approve_application_approve': ('loans_approve_application', 'approve'),
                    'loans_reject_application_reject': ('loans_reject_application', 'reject'),
                    'loans_disburse_funds_process': ('loans_disburse_funds', 'process'),
                    'loans_modify_terms_edit': ('loans_modify_terms', 'edit'),
                    'loans_rollover_loan_process': ('loans_rollover_loan', 'process'),
                    'loans_calculate_interest_calculate': ('loans_calculate_interest', 'calculate'),
                    'loans_generate_receipt_generate': ('loans_generate_receipt', 'generate'),
                    'loans_close_loan_close': ('loans_close_loan', 'close'),
                    
                    # Repayments permissions
                    'repayments_access': ('repayments', 'access'),
                    'repayments_view_list_access': ('repayments_view_list', 'access'),
                    'repayments_record_payment_create': ('repayments_record_payment', 'create'),
                    'repayments_edit_payment_edit': ('repayments_edit_payment', 'edit'),
                    'repayments_delete_payment_delete': ('repayments_delete_payment', 'delete'),
                    'repayments_verify_payment_verify': ('repayments_verify_payment', 'verify'),
                    'repayments_reconcile_mpesa_reconcile': ('repayments_reconcile_mpesa', 'reconcile'),
                    'repayments_generate_receipt_generate': ('repayments_generate_receipt', 'generate'),
                    'repayments_bulk_import_import': ('repayments_bulk_import', 'import'),
                    'repayments_view_analytics_access': ('repayments_view_analytics', 'access'),
                    'repayments_export_data_export': ('repayments_export_data', 'export'),
                    
                    # Portfolio permissions
                    'portfolio_access': ('portfolio', 'access'),
                    'portfolio_view_overview_access': ('portfolio_view_overview', 'access'),
                    'portfolio_client_assignments_manage': ('portfolio_client_assignments', 'manage'),
                    'portfolio_reassign_clients_reassign': ('portfolio_reassign_clients', 'reassign'),
                    'portfolio_performance_metrics_access': ('portfolio_performance_metrics', 'access'),
                    'portfolio_view_analytics_access': ('portfolio_view_analytics', 'access'),
                    'portfolio_generate_reports_generate': ('portfolio_generate_reports', 'generate'),
                    
                    # Reports & Statements permissions
                    'reports_statements_access': ('reports_statements', 'access'),
                    'reports_loans_due_access': ('reports_loans_due', 'access'),
                    'reports_delinquent_loans_access': ('reports_delinquent_loans', 'access'),
                    'reports_processing_fees_access': ('reports_processing_fees', 'access'),
                    'reports_interest_income_access': ('reports_interest_income', 'access'),
                    'reports_registration_fees_access': ('reports_registration_fees', 'access'),
                    'reports_collection_summary_access': ('reports_collection_summary', 'access'),
                    'reports_export_all_export': ('reports_export_all', 'export'),
                    'statements_generate_loan_generate': ('statements_generate_loan', 'generate'),
                    'statements_generate_client_generate': ('statements_generate_client', 'generate'),
                    'statements_download_pdf_download': ('statements_download_pdf', 'download'),
                    'statements_email_client_email': ('statements_email_client', 'email'),
                    
                    # Documents permissions
                    'documents_access': ('documents', 'access'),
                    'documents_upload_files_upload': ('documents_upload_files', 'upload'),
                    'documents_download_files_download': ('documents_download_files', 'download'),
                    'documents_delete_files_delete': ('documents_delete_files', 'delete'),
                    
                    # Customer Documents permissions
                    'customer_documents_access': ('customer_documents', 'access'),
                    'customer_docs_upload_kyc_upload': ('customer_docs_upload_kyc', 'upload'),
                    'customer_docs_verify_identity_verify': ('customer_docs_verify_identity', 'verify'),
                    'customer_docs_approve_kyc_approve': ('customer_docs_approve_kyc', 'approve'),
                    
                    # Payment Receipts permissions
                    'payment_receipts_access': ('payment_receipts', 'access'),
                    'receipts_generate_new_generate': ('receipts_generate_new', 'generate'),
                    'receipts_print_receipt_print': ('receipts_print_receipt', 'print'),
                    'receipts_email_client_email': ('receipts_email_client', 'email'),
                    
                    # Notifications permissions
                    'notifications_access': ('notifications', 'access'),
                    'notifications_send_individual_send': ('notifications_send_individual', 'send'),
                    'notifications_send_bulk_send': ('notifications_send_bulk', 'send'),
                    'notifications_manage_templates_manage': ('notifications_manage_templates', 'manage'),
                    
                    # Settings permissions
                    'settings_access': ('settings', 'access'),
                    'settings_edit_system_edit': ('settings_edit_system', 'edit'),
                    'settings_manage_users_manage': ('settings_manage_users', 'manage'),
                    
                    # Branch Settings permissions
                    'branch_settings_access': ('branch_settings', 'access'),
                    'branch_edit_details_edit': ('branch_edit_details', 'edit'),
                    'branch_configure_mpesa_configure': ('branch_configure_mpesa', 'configure'),
                    
                    # System Settings permissions
                    'system_settings_access': ('system_settings', 'access'),
                    'system_database_management_manage': ('system_database_management', 'manage'),
                    'system_security_settings_configure': ('system_security_settings', 'configure'),
                }
                
                # Process each permission from the form
                for form_field, (module, action) in permission_mappings.items():
                    if request.POST.get(form_field):
                        # Create custom permission
                        UserPermission.objects.create(
                            user=user,
                            module=module,
                            action=action,
                            is_allowed=True,
                            granted_by=request.user,
                            reason=f'Custom permission granted via enhanced permissions interface'
                        )
                        permissions_created += 1
                
                messages.success(request, f'Successfully updated {permissions_created} permissions for {user.get_full_name()}.')
                return redirect('users:enhanced_staff_permissions', user_id=user_id)
                
        except Exception as e:
            messages.error(request, f'Error updating permissions: {str(e)}')
    
    # Get current permissions for display
    current_permissions = {}
    user_permissions = UserPermission.objects.filter(user=user)
    
    for perm in user_permissions:
        key = f"{perm.module}_{perm.action}"
        current_permissions[key] = perm.is_allowed
    
    # Get role-based default permissions
    role_permissions = {}
    default_perms = RolePermission.objects.filter(role=user.role)
    
    for perm in default_perms:
        key = f"{perm.module}_{perm.action}"
        role_permissions[key] = perm.is_allowed
    
    context = {
        'user': user,
        'current_permissions': current_permissions,
        'role_permissions': role_permissions,
    }
    
    return render(request, 'users/enhanced_staff_permissions.html', context)


@login_required
@admin_required
def get_permission_summary(request, user_id):
    """AJAX endpoint to get permission summary for a user"""
    
    user = get_object_or_404(CustomUser, id=user_id)
    
    try:
        # Count permissions by category
        categories = {
            'dashboard': ['dashboard', 'dashboard_overview', 'dashboard_metrics', 'dashboard_charts'],
            'clients': ['clients', 'clients_view_list', 'clients_create_new', 'clients_edit_profile', 'clients_delete_client'],
            'loans': ['loans', 'loans_view_list', 'loans_create_application', 'loans_approve_application'],
            'repayments': ['repayments', 'repayments_view_list', 'repayments_record_payment'],
            'portfolio': ['portfolio', 'portfolio_view_overview', 'portfolio_client_assignments'],
            'reports': ['reports_statements', 'reports_loans_due', 'reports_delinquent_loans'],
            'documents': ['documents', 'customer_documents'],
            'settings': ['settings', 'branch_settings', 'system_settings'],
        }
        
        summary = {}
        user_permissions = UserPermission.objects.filter(user=user)
        
        for category, modules in categories.items():
            allowed_count = user_permissions.filter(
                module__in=modules, 
                is_allowed=True
            ).count()
            
            total_count = len(modules) * len(RolePermission.ACTION_CHOICES)
            
            summary[category] = {
                'allowed': allowed_count,
                'total': total_count,
                'percentage': round((allowed_count / total_count) * 100, 1) if total_count > 0 else 0
            }
        
        return JsonResponse({
            'success': True,
            'summary': summary
        })
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        })


@login_required
@admin_required
def copy_permissions_enhanced(request, from_user_id, to_user_id):
    """Copy permissions from one user to another using enhanced structure"""
    
    from_user = get_object_or_404(CustomUser, id=from_user_id)
    to_user = get_object_or_404(CustomUser, id=to_user_id)
    
    if request.method == 'POST':
        try:
            with transaction.atomic():
                # Remove existing custom permissions for target user
                UserPermission.objects.filter(user=to_user).delete()
                
                # Copy custom permissions from source user
                source_permissions = UserPermission.objects.filter(user=from_user)
                copied_count = 0
                
                for perm in source_permissions:
                    UserPermission.objects.create(
                        user=to_user,
                        module=perm.module,
                        action=perm.action,
                        is_allowed=perm.is_allowed,
                        granted_by=request.user,
                        reason=f'Copied from {from_user.get_full_name()} via enhanced permissions'
                    )
                    copied_count += 1
                
                messages.success(request, f'Successfully copied {copied_count} permissions from {from_user.get_full_name()} to {to_user.get_full_name()}.')
                
        except Exception as e:
            messages.error(request, f'Error copying permissions: {str(e)}')
    
    return redirect('users:enhanced_staff_permissions', user_id=to_user_id)


@login_required
@admin_required
def bulk_permission_update_enhanced(request):
    """Bulk update permissions for multiple users using enhanced structure"""
    
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_ids = data.get('user_ids', [])
            permissions = data.get('permissions', {})
            action_type = data.get('action_type', 'update')
            
            users = CustomUser.objects.filter(
                id__in=user_ids, 
                role__in=['admin', 'team_leader', 'loan_officer', 'secretary']
            )
            
            with transaction.atomic():
                updated_count = 0
                
                for user in users:
                    if action_type == 'apply_template':
                        # Apply a permission template
                        template_name = data.get('template_name')
                        if template_name:
                            # Remove existing custom permissions
                            UserPermission.objects.filter(user=user).delete()
                            
                            # Apply template permissions (implement template logic here)
                            # This would load from a predefined template
                            
                    elif action_type == 'grant_permissions':
                        # Grant specific permissions to users
                        for module, actions in permissions.items():
                            for action, is_allowed in actions.items():
                                if is_allowed:
                                    UserPermission.objects.get_or_create(
                                        user=user,
                                        module=module,
                                        action=action,
                                        defaults={
                                            'is_allowed': True,
                                            'granted_by': request.user,
                                            'reason': f'Bulk permission grant'
                                        }
                                    )
                    
                    updated_count += 1
                
                return JsonResponse({
                    'success': True,
                    'message': f'Successfully updated permissions for {updated_count} users.'
                })
                
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })
    
    return JsonResponse({'success': False, 'error': 'Invalid request method.'})


@login_required
@admin_required
def permission_templates_enhanced(request):
    """Manage enhanced permission templates"""
    
    # Define some common permission templates
    templates = {
        'loan_officer_basic': {
            'name': 'Loan Officer - Basic',
            'description': 'Basic permissions for loan officers',
            'permissions': {
                'dashboard_access': True,
                'clients_access': True,
                'clients_view_list_access': True,
                'clients_create_new_create': True,
                'clients_edit_profile_edit': True,
                'loans_access': True,
                'loans_view_list_access': True,
                'loans_create_application_create': True,
                'repayments_access': True,
                'repayments_record_payment_create': True,
            }
        },
        'loan_officer_advanced': {
            'name': 'Loan Officer - Advanced',
            'description': 'Advanced permissions for senior loan officers',
            'permissions': {
                'dashboard_access': True,
                'clients_access': True,
                'clients_view_list_access': True,
                'clients_create_new_create': True,
                'clients_edit_profile_edit': True,
                'clients_delete_client_delete': True,
                'loans_access': True,
                'loans_view_list_access': True,
                'loans_create_application_create': True,
                'loans_approve_application_approve': True,
                'loans_reject_application_reject': True,
                'repayments_access': True,
                'repayments_record_payment_create': True,
                'repayments_verify_payment_verify': True,
                'portfolio_access': True,
                'reports_statements_access': True,
            }
        },
        'secretary_standard': {
            'name': 'Secretary - Standard',
            'description': 'Standard permissions for secretaries',
            'permissions': {
                'dashboard_access': True,
                'clients_access': True,
                'clients_view_list_access': True,
                'clients_create_new_create': True,
                'documents_access': True,
                'customer_documents_access': True,
                'payment_receipts_access': True,
                'receipts_generate_new_generate': True,
                'notifications_access': True,
            }
        }
    }
    
    context = {
        'templates': templates,
    }
    
    return render(request, 'users/permission_templates_enhanced.html', context)