
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Count, Q
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.http import JsonResponse, HttpResponse
from django.db import transaction
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from .models import Tenant, TenantUser
from settings.models import Shop
import json
import csv
import secrets
import string

@login_required
def system_dashboard(request):
    """System health dashboard for administrators"""
    now = timezone.now()
    
    # Calculate statistics
    stats = {
        'total_tenants': Tenant.objects.count(),
        'active_tenants': Tenant.objects.filter(status='active').count(),
        'trial_tenants': Tenant.objects.filter(status='trial').count(),
        'expired_tenants': Tenant.objects.filter(status='expired').count(),
        'suspended_tenants': Tenant.objects.filter(status='suspended').count(),
        'expiring_soon': Tenant.objects.filter(
            status='trial',
            trial_ends_at__lte=now + timezone.timedelta(days=3)
        ).count(),
        'total_users': User.objects.count(),
        'total_shops': Shop.objects.count(),
        'basic_plan': Tenant.objects.filter(plan='basic').count(),
        'standard_plan': Tenant.objects.filter(plan='standard').count(),
        'premium_plan': Tenant.objects.filter(plan='premium').count(),
    }
    
    # Recent activity
    recent_signups = Tenant.objects.order_by('-created_at')[:10]
    expiring_trials = Tenant.objects.filter(
        status='trial',
        trial_ends_at__lte=now + timezone.timedelta(days=7)
    ).order_by('trial_ends_at')[:10]
    
    # Monthly growth data for charts
    monthly_signups = []
    for i in range(12):
        month_start = now.replace(day=1) - timezone.timedelta(days=30 * i)
        month_end = (month_start + timezone.timedelta(days=32)).replace(day=1) - timezone.timedelta(days=1)
        count = Tenant.objects.filter(created_at__range=[month_start, month_end]).count()
        monthly_signups.append({
            'month': month_start.strftime('%b %Y'),
            'count': count
        })
    monthly_signups.reverse()
    
    context = {
        'stats': stats,
        'recent_signups': recent_signups,
        'expiring_trials': expiring_trials,
        'monthly_signups': monthly_signups,
    }
    
    return render(request, 'admin/system_dashboard.html', context)

@login_required
def tenant_list(request):
    """List all tenants with search and filtering"""
    tenants = Tenant.objects.select_related('owner').order_by('-created_at')
    
    # Calculate stats for the header
    total_tenants = tenants.count()
    active_tenants = tenants.filter(status='active').count()
    trial_tenants = tenants.filter(status='trial').count()
    expired_tenants = tenants.filter(status='expired').count()
    
    # Search
    search = request.GET.get('search')
    if search:
        tenants = tenants.filter(
            Q(name__icontains=search) |
            Q(tenant_code__icontains=search) |
            Q(owner__username__icontains=search) |
            Q(owner__email__icontains=search) |
            Q(contact_email__icontains=search)
        )
    
    # Filter by status
    status = request.GET.get('status')
    if status:
        tenants = tenants.filter(status=status)
    
    # Filter by plan
    plan = request.GET.get('plan')
    if plan:
        tenants = tenants.filter(plan=plan)
    
    # Pagination
    paginator = Paginator(tenants, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search': search,
        'status': status,
        'plan': plan,
        'status_choices': Tenant.STATUS_CHOICES,
        'total_tenants': total_tenants,
        'active_tenants': active_tenants,
        'trial_tenants': trial_tenants,
        'expired_tenants': expired_tenants,
    }
    
    return render(request, 'admin/tenant_list.html', context)

@login_required
def tenant_detail(request, tenant_id):
    """View detailed tenant information"""
    tenant = get_object_or_404(Tenant, id=tenant_id)
    tenant_users = TenantUser.objects.filter(tenant=tenant).select_related('user')
    shops = Shop.objects.filter(tenant=tenant)
    
    context = {
        'tenant': tenant,
        'tenant_users': tenant_users,
        'shops': shops,
    }
    
    return render(request, 'admin/tenant_detail.html', context)

@login_required
def tenant_status_update(request, tenant_id):
    """Update tenant status via AJAX"""
    if request.method == 'POST':
        tenant = get_object_or_404(Tenant, id=tenant_id)
        new_status = request.POST.get('status')
        
        if new_status in dict(Tenant.STATUS_CHOICES):
            tenant.status = new_status
            tenant.save()
            
            messages.success(request, f'Tenant {tenant.name} status updated to {new_status}')
            return JsonResponse({'success': True})
        
        return JsonResponse({'success': False, 'error': 'Invalid status'})
    
    return JsonResponse({'success': False, 'error': 'Invalid request'})

@login_required
def tenant_create(request):
    """Create a new tenant"""
    if request.method == 'POST':
        # Handle tenant creation
        name = request.POST.get('name')
        tenant_code = request.POST.get('tenant_code')
        contact_email = request.POST.get('contact_email')
        owner_email = request.POST.get('owner_email')
        owner_first_name = request.POST.get('owner_first_name')
        owner_last_name = request.POST.get('owner_last_name')
        plan = request.POST.get('plan')
        status = request.POST.get('status', 'trial')
        contact_phone = request.POST.get('contact_phone')
        address = request.POST.get('address', '')
        max_shops = int(request.POST.get('max_shops', 1))
        max_users = int(request.POST.get('max_users', 5))
        send_welcome_email = request.POST.get('send_welcome_email') == 'on'
        auto_setup = request.POST.get('auto_setup') == 'on'
        
        try:
            with transaction.atomic():
                # Validate tenant code format
                import re
                if not re.match(r'^[a-zA-Z0-9]+$', tenant_code):
                    messages.error(request, 'Tenant code can only contain letters and numbers (no spaces or special characters).')
                    return render(request, 'admin/tenant_create.html', {
                        'plan_choices': Tenant.PLAN_CHOICES,
                    })
                
                # Check if tenant code is unique
                if Tenant.objects.filter(tenant_code=tenant_code).exists():
                    messages.error(request, f'Tenant code "{tenant_code}" is already taken.')
                    return render(request, 'admin/tenant_create.html', {
                        'plan_choices': Tenant.PLAN_CHOICES,
                    })
                
                # Create or get user
                # Create tenant-specific username for owner (consistent with tenant_user_create)
                email_prefix = owner_email.split('@')[0]
                base_username = f"{tenant_code}_{email_prefix}"
                username = base_username
                counter = 1
                
                # Ensure username is unique globally
                while User.objects.filter(username=username).exists():
                    username = f"{base_username}_{counter}"
                    counter += 1
                
                user, created = User.objects.get_or_create(
                    email=owner_email,
                    defaults={
                        'username': username,
                        'first_name': owner_first_name,
                        'last_name': owner_last_name,
                    }
                )
                
                password = None
                if created:
                    # Generate a stronger password with mixed case, numbers, and special chars
                    chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + "!@#$%&*"
                    password = ''.join(secrets.choice(chars) for _ in range(16))
                    user.set_password(password)
                    user.save()
                
                # Create tenant
                tenant = Tenant.objects.create(
                    name=name,
                    tenant_code=tenant_code,
                    owner=user,
                    plan=plan,
                    status=status,
                    contact_email=contact_email,
                    contact_phone=contact_phone,
                    address=address,
                    max_shops=max_shops,
                    max_users=max_users,
                )
                
                # CRITICAL: Create PostgreSQL schema for new tenant
                from .schema_utils import create_tenant_schema, migrate_tenant_schema
                import logging
                logger = logging.getLogger(__name__)
                
                try:
                    # Create the tenant schema
                    schema_created = create_tenant_schema(tenant.tenant_code)
                    if schema_created:
                        # Run migrations for the new schema to set up tables
                        migrate_tenant_schema(tenant.tenant_code)
                        logger.info(f"✅ Successfully created schema and migrated tables for tenant {tenant.tenant_code}")
                        messages.success(request, f'Tenant {name} created successfully with dedicated database schema.')
                    else:
                        logger.error(f"❌ Failed to create schema for tenant {tenant.tenant_code}")
                        messages.warning(request, f'Tenant {name} created but schema setup failed. Please contact support.')
                except Exception as e:
                    logger.error(f"❌ Error setting up schema for tenant {tenant.tenant_code}: {e}")
                    messages.warning(request, f'Tenant {name} created but schema setup failed: {str(e)}')
                    # Continue with tenant creation even if schema setup fails
                
                # Create tenant user relationship
                TenantUser.objects.create(
                    tenant=tenant,
                    user=user,
                    role='owner'
                )
                
                # Auto setup if requested
                if auto_setup:
                    try:
                        from settings.models import Shop
                        Shop.objects.create(
                            tenant=tenant,
                            name=f"{name} Main Branch",
                            address=address or "Main Location",
                            phone=contact_phone,
                            email=contact_email,
                        )
                    except:
                        pass  # Shop creation is optional
                
                # Send welcome email if requested
                if send_welcome_email and password:
                    try:
                        subject = f'Welcome to Sales Shark - Your Account is Ready!'
                        login_url = f'https://{request.get_host()}/auth/login/'
                        
                        context = {
                            'user': user,
                            'tenant': tenant,
                            'tenant_code': tenant.tenant_code,
                            'password': password,
                            'login_url': login_url,
                            'support_email': 'support@salesshark.com',
                            'contact_phone': '+254 796374224',
                        }
                        
                        html_message = render_to_string('landing/emails/welcome_email.html', context)
                        plain_message = f'''Welcome to Sales Shark!

Your organization: {tenant.name}
Tenant Code: {tenant.tenant_code}
Username: {user.username}
Password: {password}

Login at: {login_url}

Need help? Contact our support team:
Email: support@salesshark.com
Phone: +254 796374224

Thank you for choosing Sales Shark!'''
                        
                        send_mail(
                            subject=subject,
                            message=plain_message,
                            from_email=settings.DEFAULT_FROM_EMAIL,
                            recipient_list=[owner_email],
                            html_message=html_message,
                            fail_silently=False,
                        )
                        messages.success(request, f'Welcome email sent to {owner_email}')
                    except Exception as e:
                        messages.warning(request, f'Tenant created but welcome email failed: {str(e)}')
                
                messages.success(request, f'Tenant "{name}" created successfully!')
                if password:
                    messages.info(request, f'Generated password for {user.username}: {password}')
                
                return redirect('tenants_admin:tenant_detail', tenant_id=tenant.id)
                
        except Exception as e:
            messages.error(request, f'Error creating tenant: {str(e)}')
    
    context = {
        'plan_choices': Tenant.PLAN_CHOICES,
    }
    return render(request, 'admin/tenant_create.html', context)

@login_required
def tenant_edit(request, tenant_id):
    """Edit tenant details"""
    tenant = get_object_or_404(Tenant, id=tenant_id)
    
    if request.method == 'POST':
        # Validate tenant code format and uniqueness if changed
        new_tenant_code = request.POST.get('tenant_code', tenant.tenant_code)
        if new_tenant_code != tenant.tenant_code:
            import re
            if not re.match(r'^[a-zA-Z0-9]+$', new_tenant_code):
                messages.error(request, 'Tenant code can only contain letters and numbers (no spaces or special characters).')
                context = {
                    'tenant': tenant,
                    'plan_choices': Tenant.PLAN_CHOICES,
                    'status_choices': Tenant.STATUS_CHOICES,
                }
                return render(request, 'admin/tenant_edit.html', context)
                
            if Tenant.objects.filter(tenant_code=new_tenant_code).exists():
                messages.error(request, f'Tenant code "{new_tenant_code}" is already in use.')
                context = {
                    'tenant': tenant,
                    'plan_choices': Tenant.PLAN_CHOICES,
                    'status_choices': Tenant.STATUS_CHOICES,
                }
                return render(request, 'admin/tenant_edit.html', context)
        
        tenant.name = request.POST.get('name', tenant.name)
        tenant.tenant_code = new_tenant_code
        tenant.plan = request.POST.get('plan', tenant.plan)
        tenant.status = request.POST.get('status', tenant.status)
        tenant.contact_email = request.POST.get('contact_email', tenant.contact_email)
        tenant.contact_phone = request.POST.get('contact_phone', tenant.contact_phone)
        tenant.address = request.POST.get('address', tenant.address)
        tenant.max_shops = int(request.POST.get('max_shops', tenant.max_shops))
        tenant.max_users = int(request.POST.get('max_users', tenant.max_users))
        
        try:
            tenant.save()
            messages.success(request, 'Tenant updated successfully!')
            return redirect('tenants_admin:tenant_detail', tenant_id=tenant.id)
        except Exception as e:
            messages.error(request, f'Error updating tenant: {str(e)}')
    
    context = {
        'tenant': tenant,
        'plan_choices': Tenant.PLAN_CHOICES,
        'status_choices': Tenant.STATUS_CHOICES,
    }
    
    return render(request, 'admin/tenant_edit.html', context)

@login_required
def tenant_user_list(request):
    """List all tenant users with filtering"""
    tenant_users = TenantUser.objects.select_related('tenant', 'user').order_by('-joined_at')
    
    # Search functionality
    search = request.GET.get('search')
    if search:
        tenant_users = tenant_users.filter(
            Q(user__username__icontains=search) |
            Q(user__email__icontains=search) |
            Q(tenant__name__icontains=search)
        )
    
    # Filter by tenant
    tenant_filter = request.GET.get('tenant')
    if tenant_filter:
        tenant_users = tenant_users.filter(tenant__id=tenant_filter)
    
    # Filter by role
    role_filter = request.GET.get('role')
    if role_filter:
        tenant_users = tenant_users.filter(role=role_filter)
    
    # Pagination
    paginator = Paginator(tenant_users, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search': search,
        'tenant_filter': tenant_filter,
        'role_filter': role_filter,
        'tenants': Tenant.objects.all(),
        'role_choices': TenantUser.ROLE_CHOICES,
    }
    
    return render(request, 'admin/tenant_user_list.html', context)

@login_required
def tenant_user_detail(request, tenant_user_id):
    """Get tenant user details for modal display"""
    if request.method == 'GET':
        try:
            tenant_user = get_object_or_404(TenantUser, pk=tenant_user_id)
            
            user_data = {
                'id': str(tenant_user.id),
                'username': tenant_user.user.username,
                'first_name': tenant_user.user.first_name,
                'last_name': tenant_user.user.last_name,
                'full_name': tenant_user.user.get_full_name(),
                'email': tenant_user.user.email,
                'tenant_name': tenant_user.tenant.name,
                'role': tenant_user.role,
                'is_active': tenant_user.is_active,
                'joined_at': tenant_user.joined_at.strftime('%B %d, %Y'),
            }
            
            return JsonResponse({'success': True, 'user': user_data})
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_user_edit(request, tenant_user_id):
    """Edit tenant user details"""
    if request.method == 'POST':
        try:
            tenant_user = get_object_or_404(TenantUser, pk=tenant_user_id)
            
            user = tenant_user.user
            
            # Update user details
            user.first_name = request.POST.get('first_name', '')
            user.last_name = request.POST.get('last_name', '')
            user.username = request.POST.get('username', user.username)
            user.email = request.POST.get('email', user.email)
            
            # Update password if provided
            new_password = request.POST.get('new_password')
            if new_password and new_password.strip():
                user.set_password(new_password)
            
            user.save()
            
            # Update tenant user details
            tenant_user.role = request.POST.get('role', tenant_user.role)
            tenant_user.is_active = request.POST.get('is_active') == 'true'
            tenant_user.save()
            
            return JsonResponse({
                'success': True,
                'message': 'User updated successfully'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_user_reset_password(request, tenant_user_id):
    """Reset tenant user password"""
    if request.method == 'POST':
        try:
            tenant_user = get_object_or_404(TenantUser, pk=tenant_user_id)
            
            user = tenant_user.user
            
            # Generate new stronger password
            chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + "!@#$%&*"
            password = ''.join(secrets.choice(chars) for _ in range(16))
            user.set_password(password)
            user.save()
            
            # Send password reset email
            try:
                subject = f'Password Reset - {tenant_user.tenant.name}'
                login_url = f'http://{request.get_host()}/auth/login/'
                
                context = {
                    'user': user,
                    'tenant': tenant_user.tenant,
                    'tenant_code': tenant_user.tenant.tenant_code,
                    'new_password': password,
                    'login_url': login_url,
                    'support_email': 'support@posapp.co.ke',
                    'contact_phone': '+254 796374224',
                }
                
                html_message = render_to_string('tenants/emails/password_reset.html', context)
                plain_message = f'''Password Reset - {tenant_user.tenant.name}

Hello {user.get_full_name() or user.username},

Your password has been reset by an administrator.

Your new login credentials:
Username: {user.username}
New Password: {password}
Tenant Code: {tenant_user.tenant.tenant_code}

Login at: {login_url}

IMPORTANT: For security reasons, please change this password after your first login.

Support: support@posapp.co.ke
Phone: +254 796374224

Best regards,
The POS 254 Team'''
                
                send_mail(
                    subject=subject,
                    message=plain_message,
                    from_email=settings.DEFAULT_FROM_EMAIL,
                    recipient_list=[user.email],
                    html_message=html_message,
                    fail_silently=False,
                )
                
                return JsonResponse({
                    'success': True,
                    'message': f'Password reset and sent to {user.email}. New password: {password}'
                })
                
            except Exception as e:
                return JsonResponse({
                    'success': True,
                    'message': f'Password reset successfully. New password: {password}. Email failed: {str(e)}'
                })
                
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_user_remove(request, tenant_user_id):
    """Remove user from tenant"""
    if request.method == 'POST':
        try:
            tenant_user = get_object_or_404(TenantUser, pk=tenant_user_id)
            
            user_name = tenant_user.user.get_full_name() or tenant_user.user.username
            tenant_name = tenant_user.tenant.name
            
            # Don't allow removal of the last owner
            if tenant_user.role == 'owner':
                owners_count = TenantUser.objects.filter(
                    tenant=tenant_user.tenant, 
                    role='owner'
                ).count()
                if owners_count <= 1:
                    return JsonResponse({
                        'success': False, 
                        'error': 'Cannot remove the last owner of the tenant'
                    })
            
            tenant_user.delete()
            
            return JsonResponse({
                'success': True,
                'message': f'{user_name} removed from {tenant_name}'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_user_create(request):
    """Create a new tenant user"""
    if request.method == 'POST':
        tenant_id = request.POST.get('tenant')
        user_email = request.POST.get('user_email')
        role = request.POST.get('role')
        
        try:
            tenant = get_object_or_404(Tenant, id=tenant_id)
            
            # Create or get user with tenant-specific username generation
            # Use tenant code prefix to ensure unique usernames per tenant
            email_prefix = user_email.split('@')[0]
            base_username = f"{tenant.tenant_code}_{email_prefix}"
            username = base_username
            counter = 1
            
            # Ensure username is unique globally (in case tenant codes overlap)
            while User.objects.filter(username=username).exists():
                username = f"{base_username}_{counter}"
                counter += 1
            
            user, created = User.objects.get_or_create(
                email=user_email,
                defaults={
                    'username': username,
                    'first_name': request.POST.get('first_name', ''),
                    'last_name': request.POST.get('last_name', ''),
                }
            )
            
            password = None
            if created:
                custom_password = request.POST.get('password')
                if custom_password and custom_password.strip():
                    password = custom_password
                else:
                    # Generate a stronger password with mixed case, numbers, and special chars
                    import random
                    chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + "!@#$%&*"
                    password = ''.join(secrets.choice(chars) for _ in range(16))
                    
                user.set_password(password)
                user.save()
            
            # Create tenant user relationship
            tenant_user, created_tenant_user = TenantUser.objects.get_or_create(
                tenant=tenant,
                user=user,
                defaults={'role': role}
            )
            
            if created_tenant_user:
                # Send welcome email with login credentials
                try:
                    subject = f'Welcome to {tenant.name} - Your Account is Ready!'
                    login_url = f'http://{request.get_host()}/auth/login/'
                    
                    context = {
                        'user': user,
                        'tenant': tenant,
                        'tenant_code': tenant.tenant_code,
                        'password': password,
                        'login_url': login_url,
                        'role': role,
                        'support_email': 'support@salesshark.com',
                        'contact_phone': '+254 796374224',
                    }
                    
                    html_message = render_to_string('tenants/emails/tenant_user_welcome.html', context)
                    plain_message = f'''Welcome to {tenant.name}!

Hello {user.get_full_name() or user.username},

You have been added to {tenant.name} as a {role}.

Your login credentials:
Username: {user.username}
Password: {password if password else 'Use your existing password'}
Tenant Code: {tenant.tenant_code}

Login at: {login_url}

Need help? Contact our support team:
Email: support@salesshark.com
Phone: +254 796374224

Thank you for using Sales Shark!'''
                    
                    send_mail(
                        subject=subject,
                        message=plain_message,
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        recipient_list=[user_email],
                        html_message=html_message,
                        fail_silently=False,
                    )
                    
                    messages.success(request, f'User added to {tenant.name} successfully! Welcome email sent to {user_email}')
                    # Don't display password in messages for security
                        
                except Exception as e:
                    messages.success(request, f'User added to {tenant.name} successfully!')
                    messages.warning(request, f'Welcome email failed to send: {str(e)}')
                    
            else:
                messages.warning(request, 'User already exists in this tenant.')
                
            return redirect('tenants_admin:tenant_user_list')
            
        except Exception as e:
            messages.error(request, f'Error creating tenant user: {str(e)}')
    
    context = {
        'tenants': Tenant.objects.all(),
        'role_choices': TenantUser.ROLE_CHOICES,
    }
    
    return render(request, 'admin/tenant_user_create.html', context)

@login_required
def subscription_list(request):
    """List all subscriptions"""
    from .models import Subscription
    subscriptions = Subscription.objects.select_related('tenant').order_by('-created_at')
    
    # Filter by status
    status = request.GET.get('status')
    if status:
        subscriptions = subscriptions.filter(payment_status=status)
    
    # Pagination
    paginator = Paginator(subscriptions, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'status': status,
        'status_choices': Subscription.PAYMENT_STATUS_CHOICES,
    }
    
    return render(request, 'admin/subscription_list.html', context)

@login_required
def billing_overview(request):
    """Billing overview and analytics"""
    from .models import Subscription
    from django.db.models import Sum
    
    now = timezone.now()
    
    # Calculate billing stats
    billing_stats = {
        'total_revenue': Subscription.objects.filter(payment_status='paid').aggregate(
            total=Sum('amount')
        )['total'] or 0,
        'monthly_revenue': Subscription.objects.filter(
            payment_status='paid',
            start_date__month=now.month,
            start_date__year=now.year
        ).aggregate(total=Sum('amount'))['total'] or 0,
        'pending_payments': Subscription.objects.filter(payment_status='pending').count(),
        'failed_payments': Subscription.objects.filter(payment_status='failed').count(),
    }
    
    context = {
        'billing_stats': billing_stats,
    }
    
    return render(request, 'admin/billing_overview.html', context)

@login_required
def system_settings(request):
    """System-wide settings"""
    if request.method == 'POST':
        # Handle system settings updates
        messages.success(request, 'System settings updated successfully!')
    
    return render(request, 'admin/system_settings.html')

@login_required
def tenant_export(request):
    """Export tenant data as CSV"""
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="tenants_export.csv"'
    
    writer = csv.writer(response)
    writer.writerow([
        'Name', 'Slug', 'Owner Name', 'Owner Email', 'Contact Email', 
        'Contact Phone', 'Plan', 'Status', 'Days Remaining', 'Max Shops', 
        'Max Users', 'Created At', 'Trial Ends At'
    ])
    
    tenants = Tenant.objects.select_related('owner').all()
    for tenant in tenants:
        writer.writerow([
            tenant.name,
            tenant.slug,
            tenant.owner.get_full_name() or tenant.owner.username,
            tenant.owner.email,
            tenant.contact_email,
            tenant.contact_phone,
            tenant.get_plan_display(),
            tenant.get_status_display(),
            tenant.days_remaining,
            tenant.max_shops,
            tenant.max_users,
            tenant.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            tenant.trial_ends_at.strftime('%Y-%m-%d %H:%M:%S') if tenant.trial_ends_at else '',
        ])
    
    return response

@login_required
def bulk_status_update(request):
    """Bulk update tenant status"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            tenant_ids = data.get('tenant_ids', [])
            new_status = data.get('status')
            
            if not tenant_ids or not new_status:
                return JsonResponse({'success': False, 'error': 'Invalid data'})
            
            if new_status not in dict(Tenant.STATUS_CHOICES):
                return JsonResponse({'success': False, 'error': 'Invalid status'})
            
            updated_count = Tenant.objects.filter(id__in=tenant_ids).update(status=new_status)
            
            return JsonResponse({
                'success': True, 
                'updated_count': updated_count,
                'message': f'Updated {updated_count} tenants to {new_status}'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def bulk_send_reminders(request):
    """Send reminder emails to selected tenants"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            tenant_ids = data.get('tenant_ids', [])
            
            if not tenant_ids:
                return JsonResponse({'success': False, 'error': 'No tenants selected'})
            
            tenants = Tenant.objects.filter(id__in=tenant_ids)
            sent_count = 0
            
            for tenant in tenants:
                try:
                    subject = f'Trial Reminder - {tenant.name}'
                    message = f'''
Hello {tenant.owner.get_full_name() or tenant.owner.username},

This is a reminder about your Sales Shark trial for {tenant.name}.

Days remaining: {tenant.days_remaining}
Status: {tenant.get_status_display()}

To continue using Sales Shark after your trial, please upgrade your plan.

Login at: http://{request.get_host()}/auth/login/
Tenant Code: {tenant.tenant_code}

Thank you for choosing Sales Shark!
'''
                    
                    send_mail(
                        subject=subject,
                        message=message,
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        recipient_list=[tenant.contact_email],
                        fail_silently=True,
                    )
                    sent_count += 1
                except:
                    continue
            
            return JsonResponse({
                'success': True,
                'sent_count': sent_count,
                'message': f'Sent reminders to {sent_count} tenants'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def send_trial_reminders(request):
    """Send trial reminder emails to tenants with trials expiring soon"""
    if request.method == 'POST':
        try:
            now = timezone.now()
            expiring_tenants = Tenant.objects.filter(
                status='trial',
                trial_ends_at__lte=now + timezone.timedelta(days=7),
                trial_ends_at__gte=now
            )
            
            sent_count = 0
            for tenant in expiring_tenants:
                try:
                    subject = f'Your Sales Shark Trial Expires Soon - {tenant.name}'
                    message = f'''
Hello {tenant.owner.get_full_name() or tenant.owner.username},

Your Sales Shark trial for {tenant.name} expires in {tenant.days_remaining} days.

To continue using Sales Shark, please upgrade to a paid plan before your trial expires.

Current plan: {tenant.get_plan_display()}
Status: {tenant.get_status_display()}

Login to upgrade: http://{request.get_host()}/auth/login/
Tenant Code: {tenant.tenant_code}

Need help? Contact our support team.

Thank you for choosing Sales Shark!
'''
                    
                    send_mail(
                        subject=subject,
                        message=message,
                        from_email=settings.DEFAULT_FROM_EMAIL,
                        recipient_list=[tenant.contact_email],
                        fail_silently=True,
                    )
                    sent_count += 1
                except:
                    continue
            
            return JsonResponse({
                'success': True,
                'sent_count': sent_count,
                'message': f'Sent trial reminders to {sent_count} tenants'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_send_reminder(request, tenant_id):
    """Send reminder email to specific tenant"""
    if request.method == 'POST':
        try:
            tenant = get_object_or_404(Tenant, id=tenant_id)
            
            subject = f'Account Reminder - {tenant.name}'
            message = f'''
Hello {tenant.owner.get_full_name() or tenant.owner.username},

This is a reminder about your Sales Shark account for {tenant.name}.

Status: {tenant.get_status_display()}
Plan: {tenant.get_plan_display()}
Days remaining: {tenant.days_remaining}

Login at: http://{request.get_host()}/auth/login/
Tenant Code: {tenant.tenant_code}

If you need assistance, please contact our support team.

Thank you for choosing Sales Shark!
'''
            
            send_mail(
                subject=subject,
                message=message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[tenant.contact_email],
                fail_silently=False,
            )
            
            return JsonResponse({
                'success': True,
                'message': f'Reminder sent to {tenant.contact_email}'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_send_email(request, tenant_id):
    """Send custom email to specific tenant"""
    if request.method == 'POST':
        try:
            tenant = get_object_or_404(Tenant, id=tenant_id)
            
            subject = request.POST.get('subject')
            message = request.POST.get('message')
            recipient = request.POST.get('recipient', tenant.contact_email)
            send_copy = request.POST.get('send_copy') == 'on'
            
            if not subject or not message:
                return JsonResponse({'success': False, 'error': 'Subject and message are required'})
            
            # Replace template variables
            login_url = f'http://{request.get_host()}/auth/login/'
            replacements = {
                '{tenant_name}': tenant.name,
                '{tenant_code}': tenant.tenant_code,
                '{owner_name}': tenant.owner.get_full_name() or tenant.owner.username,
                '{contact_email}': tenant.contact_email,
                '{login_url}': login_url,
            }
            
            for placeholder, value in replacements.items():
                subject = subject.replace(placeholder, value)
                message = message.replace(placeholder, value)
            
            # Prepare recipient list
            recipient_list = [recipient]
            if send_copy:
                recipient_list.append(request.user.email)
            
            send_mail(
                subject=subject,
                message=message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=recipient_list,
                fail_silently=False,
            )
            
            return JsonResponse({
                'success': True,
                'message': f'Email sent to {recipient}'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_send_invitation(request, tenant_id):
    """Send invitation email to join tenant"""
    if request.method == 'POST':
        try:
            tenant = get_object_or_404(Tenant, id=tenant_id)
            
            email = request.POST.get('email')
            role = request.POST.get('role')
            first_name = request.POST.get('first_name', '')
            last_name = request.POST.get('last_name', '')
            personal_message = request.POST.get('personal_message', '')
            create_account = request.POST.get('create_account') == 'on'
            
            if not email or not role:
                return JsonResponse({'success': False, 'error': 'Email and role are required'})
            
            account_created = False
            password = None
            
            # Create user account if requested
            if create_account:
                # Check if user already exists
                existing_user = User.objects.filter(email=email).first()
                if existing_user:
                    # Check if user is already part of this tenant
                    existing_tenant_user = TenantUser.objects.filter(
                        tenant=tenant, 
                        user=existing_user
                    ).first()
                    
                    if existing_tenant_user:
                        return JsonResponse({
                            'success': False, 
                            'error': 'User is already a member of this tenant'
                        })
                    
                    # Add existing user to tenant
                    TenantUser.objects.create(
                        tenant=tenant,
                        user=existing_user,
                        role=role
                    )
                    user = existing_user
                else:
                    # Create new user
                    username = email.split('@')[0]
                    counter = 1
                    original_username = username
                    while User.objects.filter(username=username).exists():
                        username = f"{original_username}{counter}"
                        counter += 1
                    
                    # Generate stronger password
                    chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + "!@#$%&*"
                    password = ''.join(secrets.choice(chars) for _ in range(16))
                    
                    user = User.objects.create_user(
                        username=username,
                        email=email,
                        first_name=first_name,
                        last_name=last_name,
                        password=password
                    )
                    
                    # Add user to tenant
                    TenantUser.objects.create(
                        tenant=tenant,
                        user=user,
                        role=role
                    )
                    account_created = True
            
            # Prepare email content
            subject = f'Invitation to join {tenant.name} on Sales Shark'
            login_url = f'http://{request.get_host()}/auth/login/'
            
            if create_account and account_created:
                message = f'''Hello {first_name or 'there'},

You have been invited to join {tenant.name} on Sales Shark as a {role}.

Your account has been created with the following credentials:
Username: {user.username}
Password: {password}
Tenant Code: {tenant.tenant_code}

Login at: {login_url}

{personal_message}

Welcome to Sales Shark!

Best regards,
Sales Shark Team'''
            else:
                message = f'''Hello {first_name or 'there'},

You have been invited to join {tenant.name} on Sales Shark as a {role}.

Tenant Code: {tenant.tenant_code}
Login at: {login_url}

{personal_message}

If you don't have an account yet, please contact the administrator for account creation.

Best regards,
Sales Shark Team'''
            
            send_mail(
                subject=subject,
                message=message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[email],
                fail_silently=False,
            )
            
            return JsonResponse({
                'success': True,
                'message': f'Invitation sent to {email}',
                'account_created': account_created
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

@login_required
def tenant_delete(request, tenant_id):
    """Delete tenant (dangerous operation)"""
    if request.method == 'DELETE':
        try:
            tenant = get_object_or_404(Tenant, id=tenant_id)
            tenant_name = tenant.name
            
            # This will cascade delete all related data
            tenant.delete()
            
            return JsonResponse({
                'success': True,
                'message': f'Tenant "{tenant_name}" deleted successfully'
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return JsonResponse({'success': False, 'error': 'Invalid request method'})

def tenant_suspended(request, tenant_code=None):
    """Display suspended tenant page"""
    tenant = None
    if tenant_code:
        tenant = get_object_or_404(Tenant, tenant_code=tenant_code, status='suspended')
    else:
        # Get tenant from session if available
        session_tenant_code = request.session.get('tenant_code')
        if session_tenant_code:
            try:
                tenant = Tenant.objects.get(tenant_code=session_tenant_code, status='suspended')
            except Tenant.DoesNotExist:
                pass
    
    context = {
        'tenant': tenant,
    }
    
    return render(request, 'admin/tenant_suspended.html', context)

@login_required
def tenant_switch(request):
    """Allow users to switch between tenants they have access to"""
    if request.user.is_superuser:
        # Superusers can access any tenant
        tenant_users = TenantUser.objects.select_related('tenant').order_by('tenant__name')
    else:
        # Regular users can only access their assigned tenants
        tenant_users = TenantUser.objects.filter(
            user=request.user, 
            is_active=True
        ).select_related('tenant').order_by('tenant__name')
    
    if request.method == 'POST':
        tenant_id = request.POST.get('tenant_id')
        if tenant_id:
            tenant = get_object_or_404(Tenant, id=tenant_id)
            # Set tenant in session and redirect to dashboard
            request.session['tenant_code'] = tenant.tenant_code
            return redirect('dashboard')
    
    context = {
        'tenant_users': tenant_users,
    }
    
    return render(request, 'admin/tenant_switch.html', context)
