"""
Management command to send example emails for all email-sending locations in the system.
This helps visualize how each email will look when sent.

Usage:
    python manage.py send_example_emails --recipient=test@example.com
    python manage.py send_example_emails --recipient=test@example.com --dry-run
"""

import os
from datetime import datetime, timedelta

from django.conf import settings
from django.core.mail import EmailMultiAlternatives, send_mail
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.html import strip_tags


class Command(BaseCommand):
    help = 'Send example emails for all email-sending locations to visualize their appearance'

    def add_arguments(self, parser):
        parser.add_argument(
            '--recipient',
            type=str,
            required=True,
            help='Email address to send examples to',
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Print email details to console instead of sending',
        )
        parser.add_argument(
            '--category',
            type=str,
            help='Send only emails from a specific category (accounts, complaints, observations, organizations, analytics, appreciation, surveys, core)',
        )

    def handle(self, *args, **options):
        self.recipient = options['recipient']
        self.dry_run = options['dry_run']
        self.category = options.get('category')

        self.stdout.write(self.style.SUCCESS(f'\n{"="*80}'))
        self.stdout.write(self.style.SUCCESS(f'Example Email Sender'))
        self.stdout.write(self.style.SUCCESS(f'{"="*80}'))
        self.stdout.write(self.style.SUCCESS(f'Recipient: {self.recipient}'))
        self.stdout.write(self.style.SUCCESS(f'Dry Run: {self.dry_run}'))
        if self.category:
            self.stdout.write(self.style.SUCCESS(f'Category: {self.category}'))
        self.stdout.write(self.style.SUCCESS(f'{"="*80}\n'))

        sent_count = 0
        failed_count = 0

        # Accounts/Onboarding Emails
        if not self.category or self.category == 'accounts':
            self.stdout.write(self.style.WARNING('\n📧 ACCOUNTS / ONBOARDING EMAILS\n'))

            try:
                self._send_onboarding_invitation()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Onboarding Invitation: {str(e)}'))
                failed_count += 1

            try:
                self._send_onboarding_reminder()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Onboarding Reminder: {str(e)}'))
                failed_count += 1

            try:
                self._send_onboarding_completion()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Onboarding Completion: {str(e)}'))
                failed_count += 1

            try:
                self._send_invitation_expired()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Invitation Expired: {str(e)}'))
                failed_count += 1

        # Organizations Emails
        if not self.category or self.category == 'organizations':
            self.stdout.write(self.style.WARNING('\n📧 ORGANIZATIONS EMAILS\n'))

            try:
                self._send_staff_password_reset()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Staff Password Reset: {str(e)}'))
                failed_count += 1

        # Complaints Emails
        if not self.category or self.category == 'complaints':
            self.stdout.write(self.style.WARNING('\n📧 COMPLAINTS EMAILS\n'))

            try:
                self._send_explanation_request()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Explanation Request: {str(e)}'))
                failed_count += 1

            try:
                self._send_explanation_reminder()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Explanation Reminder: {str(e)}'))
                failed_count += 1

            try:
                self._send_explanation_second_reminder()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Explanation 2nd Reminder: {str(e)}'))
                failed_count += 1

            try:
                self._send_sla_reminder()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ SLA Reminder: {str(e)}'))
                failed_count += 1

            try:
                self._send_sla_second_reminder()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ SLA 2nd Reminder: {str(e)}'))
                failed_count += 1

            try:
                self._send_complaint_notification_inline()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Complaint Notification (inline): {str(e)}'))
                failed_count += 1

            try:
                self._send_complaint_resolution_inline()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Complaint Resolution (inline): {str(e)}'))
                failed_count += 1

            try:
                self._send_admin_new_complaint_inline()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Admin New Complaint (inline): {str(e)}'))
                failed_count += 1

            try:
                self._send_escalation_inline()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Escalation (inline): {str(e)}'))
                failed_count += 1

        # Observations Emails
        if not self.category or self.category == 'observations':
            self.stdout.write(self.style.WARNING('\n📧 OBSERVATIONS EMAILS\n'))

            try:
                self._send_new_observation()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ New Observation: {str(e)}'))
                failed_count += 1

            try:
                self._send_observation_assigned()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Observation Assigned: {str(e)}'))
                failed_count += 1

            try:
                self._send_observation_resolved()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Observation Resolved: {str(e)}'))
                failed_count += 1

            try:
                self._send_observation_sla_reminder()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Observation SLA Reminder: {str(e)}'))
                failed_count += 1

            try:
                self._send_observation_monthly_followup()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Observation Monthly Followup: {str(e)}'))
                failed_count += 1

        # Analytics Emails
        if not self.category or self.category == 'analytics':
            self.stdout.write(self.style.WARNING('\n📧 ANALYTICS EMAILS\n'))

            try:
                self._send_px_digest()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ PX Digest: {str(e)}'))
                failed_count += 1

        # Surveys Emails
        if not self.category or self.category == 'surveys':
            self.stdout.write(self.style.WARNING('\n📧 SURVEYS EMAILS\n'))

            try:
                self._send_survey_invitation()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Survey Invitation: {str(e)}'))
                failed_count += 1

            try:
                self._send_survey_invitation_template()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Survey Invitation (template): {str(e)}'))
                failed_count += 1

        # Appreciation Emails
        if not self.category or self.category == 'appreciation':
            self.stdout.write(self.style.WARNING('\n📧 APPRECIATION EMAILS\n'))

            try:
                self._send_appreciation_notification()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Appreciation Notification: {str(e)}'))
                failed_count += 1

        # Core/Public Emails
        if not self.category or self.category == 'core':
            self.stdout.write(self.style.WARNING('\n📧 CORE / PUBLIC EMAILS\n'))

            try:
                self._send_public_inquiry()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Public Inquiry: {str(e)}'))
                failed_count += 1

        # Notification Settings Service Emails (currently inline)
        if not self.category or self.category == 'settings':
            self.stdout.write(self.style.WARNING('\n📧 NOTIFICATION SETTINGS SERVICE EMAILS\n'))

            try:
                self._send_explanation_requested()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Explanation Requested: {str(e)}'))
                failed_count += 1

            try:
                self._send_complaint_assigned()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Complaint Assigned: {str(e)}'))
                failed_count += 1

            try:
                self._send_complaint_status_changed()
                sent_count += 1
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'❌ Complaint Status Changed: {str(e)}'))
                failed_count += 1

        # Summary
        self.stdout.write(self.style.SUCCESS(f'\n{"="*80}'))
        self.stdout.write(self.style.SUCCESS(f'✅ Summary'))
        self.stdout.write(self.style.SUCCESS(f'{"="*80}'))
        self.stdout.write(self.style.SUCCESS(f'Total Sent/Displayed: {sent_count}'))
        self.stdout.write(self.style.SUCCESS(f'Failed: {failed_count}'))
        self.stdout.write(self.style.SUCCESS(f'{"="*80}\n'))

        if self.dry_run:
            self.stdout.write(self.style.WARNING('💡 DRY RUN MODE: Emails were printed to console, not actually sent.\n'))
        else:
            self.stdout.write(self.style.SUCCESS(f'✅ All example emails sent to {self.recipient}\n'))

    def _send_email(self, subject, html_content, text_content, extra_context=None):
        """Helper to send or display email"""
        if self.dry_run:
            self.stdout.write(self.style.SUCCESS(f'{"─"*80}'))
            self.stdout.write(self.style.SUCCESS(f'Subject: {subject}'))
            self.stdout.write(self.style.SUCCESS(f'To: {self.recipient}'))
            self.stdout.write(self.style.SUCCESS(f'{"─"*80}'))
            self.stdout.write(self.style.SUCCESS(f'\n📄 PLAIN TEXT VERSION:\n{text_content[:500]}...\n'))
            self.stdout.write(self.style.SUCCESS(f'📄 HTML VERSION: (see rendered email)\n'))
            self.stdout.write(self.style.SUCCESS(f'{"─"*80}\n'))
            return True
        else:
            email = EmailMultiAlternatives(
                subject=subject,
                body=text_content,
                from_email=settings.DEFAULT_FROM_EMAIL,
                to=[self.recipient],
            )
            email.attach_alternative(html_content, 'text/html')
            email.send()
            self.stdout.write(self.style.SUCCESS(f'✅ Sent: {subject}'))
            return True

    # ========================================================================
    # ACCOUNTS / ONBOARDING EMAILS
    # ========================================================================

    def _send_onboarding_invitation(self):
        """Example onboarding invitation email (uses template)"""
        context = {
            'user': type('obj', (object,), {'first_name': 'Ahmed', 'email': 'ahmed@hospital.com'})(),
            'activation_url': 'https://px360.sa/onboarding/setup/abc123token',
            'expires_at': 'April 12, 2026',
            'days_remaining': 7,
        }
        html_content = render_to_string('accounts/onboarding/invitation_email.html', context)
        text_content = f"""
        Welcome to PX360!
        
        Hello Ahmed,
        
        You have been invited to join PX360, our comprehensive Patient Experience management platform.
        
        During the onboarding process, you will:
        ✓ Learn about PX360 features and your role responsibilities
        ✓ Set up your profile and preferences
        ✓ Complete required training materials
        ✓ Activate your account and start using PX360
        
        Click here to complete your account setup: https://px360.sa/onboarding/setup/abc123token
        
        Important: This invitation link will expire in 7 days.
        
        If you have any questions, contact support@alhammadi.com or call +966 11 123 4567.
        """
        self._send_email('Welcome to PX360 - Al Hammadi Hospital', html_content, text_content)

    def _send_onboarding_reminder(self):
        """Example onboarding reminder email (uses template)"""
        context = {
            'user': type('obj', (object,), {'first_name': 'Sara', 'email': 'sara@hospital.com'})(),
            'activation_url': 'https://px360.sa/onboarding/setup/reminder456token',
            'expires_at': 'April 12, 2026',
            'days_remaining': 3,
        }
        html_content = render_to_string('accounts/onboarding/reminder_email.html', context)
        text_content = """
        Reminder: Complete Your PX360 Account Setup
        
        Hello Sara,
        
        This is a friendly reminder to complete your account setup for PX360.
        
        Click here to get started: https://px360.sa/onboarding/setup/reminder456token
        
        This link will expire soon. Please complete your setup as soon as possible.
        """
        self._send_email('Reminder: Complete Your PX360 Setup', html_content, text_content)

    def _send_onboarding_completion(self):
        """Example onboarding completion email (uses template)"""
        context = {
            'user': type('obj', (object,), {
                'first_name': 'Mohammed',
                'email': 'mohammed@hospital.com',
                'get_full_name': lambda: 'Mohammed Al-Sayed',
                'department': type('obj', (object,), {'name': 'Patient Experience'})(),
            })(),
            'user_detail_url': 'https://px360.sa/accounts/onboarding/provisional/mohammed/progress/',
            'role_display': 'PX Employee',
            'completed_at': 'April 5, 2026 09:30',
        }
        html_content = render_to_string('accounts/onboarding/completion_email.html', context)
        text_content = """
        Welcome to PX360!
        
        Hello Mohammed,
        
        Congratulations! Your account setup is now complete.
        
        You can now log in to PX360 and start using the system.
        
        Login URL: https://px360.sa/login
        
        If you need any assistance, please contact our support team.
        """
        self._send_email('Welcome to PX360! Your Account is Ready', html_content, text_content)

    def _send_invitation_expired(self):
        """Example invitation expired email"""
        context = {
            'user_email': 'expired@hospital.com',
        }
        html_content = render_to_string('emails/invitation_expired.html', context)
        text_content = """
        Invitation Expired
        
        Your invitation to join PX360 has expired.
        
        Please contact your administrator to request a new invitation link.
        
        Email: expired@hospital.com
        """
        self._send_email('Your PX360 Invitation Has Expired', html_content, text_content)

    # ========================================================================
    # ORGANIZATIONS EMAILS
    # ========================================================================

    def _send_staff_password_reset(self):
        """Example staff password reset email (uses template)"""
        context = {
            'staff': type('obj', (object,), {
                'get_full_name': lambda: 'Dr. Fatima Al-Rashid',
                'email': 'fatima@hospital.com',
            })(),
            'user': type('obj', (object,), {'username': 'fatima.alrashid'})(),
            'reset_url': 'https://px360.sa/accounts/password/reset/abc123token/',
        }
        html_content = render_to_string('organizations/emails/staff_credentials.html', context)
        text_content = f"""
        Your PX360 Account Password Setup
        
        Dear Dr. Fatima Al-Rashid,
        
        Your account has been created. For your security, no password is sent by email.
        
        Username: fatima.alrashid
        Email: fatima@hospital.com
        
        Set password: https://px360.sa/accounts/password/reset/abc123token/
        
        This link expires in 24 hours.
        """
        self._send_email('Set Your PX360 Password', html_content, text_content)

    # ========================================================================
    # COMPLAINTS EMAILS
    # ========================================================================

    def _send_explanation_request(self):
        """Example explanation request email (uses template)"""
        context = {
            'staff_name': 'Nurse Amira Hassan',
            'complaint_id': 'COMP-2026-0042',
            'complaint_title': 'Long Wait Time at Emergency Department',
            'patient_name': 'Mr. Khalid Al-Mansoori',
            'hospital_name': 'Al Hammadi Hospital - Main Branch',
            'department_name': 'Emergency Department',
            'category': 'Service Quality',
            'status': 'Pending Explanation',
            'created_date': 'April 5, 2026',
            'description': 'Patient waited over 3 hours to be seen by a physician. Patient expressed frustration and dissatisfaction with the service.',
            'explanation_url': 'https://px360.sa/complaints/explain/xyz789token',
            'custom_message': 'Please prioritize this response as the patient is expecting feedback within 48 hours.',
        }
        html_content = render_to_string('emails/explanation_request.html', context)
        text_content = f"""
        Explanation Request
        
        Dear {context['staff_name']},
        
        You have been assigned to provide an explanation for the following patient complaint:
        
        Reference: #{context['complaint_id']}
        Title: {context['complaint_title']}
        Patient: {context['patient_name']}
        Hospital: {context['hospital_name']}
        Department: {context['department_name']}
        Category: {context['category']}
        Status: {context['status']}
        Date: {context['created_date']}
        
        Description: {context['description']}
        
        Note from PX Team: {context['custom_message']}
        
        Submit your explanation here: {context['explanation_url']}
        """
        self._send_email('Explanation Request - Al Hammadi Hospital', html_content, text_content)

    def _send_explanation_reminder(self):
        """Example explanation reminder email (uses template)"""
        context = {
            'staff_name': 'Dr. Omar Abdullah',
            'complaint_id': 'COMP-2026-0038',
            'complaint_title': 'Billing Dispute for Laboratory Tests',
            'deadline': 'April 9, 2026',
            'explanation_url': 'https://px360.sa/complaints/explain/reminder123token',
        }
        html_content = render_to_string('emails/explanation_reminder.html', context)
        text_content = f"""
        Reminder: Explanation Request
        
        Dear {context['staff_name']},
        
        This is a friendly reminder that the explanation for complaint #{context['complaint_id']} is due by {context['deadline']}.
        
        Please submit your response as soon as possible.
        
        Submit here: {context['explanation_url']}
        """
        self._send_email('Reminder: Explanation Request Due Soon', html_content, text_content)

    def _send_explanation_second_reminder(self):
        """Example explanation second reminder email (uses template)"""
        context = {
            'staff_name': 'Dr. Omar Abdullah',
            'complaint_id': 'COMP-2026-0038',
            'complaint_title': 'Billing Dispute for Laboratory Tests',
            'deadline': 'April 9, 2026',
            'explanation_url': 'https://px360.sa/complaints/explain/reminder123token',
        }
        html_content = render_to_string('emails/explanation_second_reminder.html', context)
        text_content = f"""
        SECOND REMINDER: Explanation Request
        
        Dear {context['staff_name']},
        
        This is a second reminder for complaint #{context['complaint_id']}. The deadline is {context['deadline']}.
        
        This is urgent. Please respond immediately.
        
        Submit here: {context['explanation_url']}
        """
        self._send_email('URGENT: Second Reminder - Explanation Request', html_content, text_content)

    def _send_sla_reminder(self):
        """Example SLA reminder email (uses template)"""
        context = {
            'staff_name': 'Manager Hassan Al-Balushi',
            'complaint_id': 'COMP-2026-0035',
            'complaint_title': 'Unprofessional Behavior of Staff Member',
            'sla_deadline': 'April 12, 2026',
            'days_remaining': '5 days',
        }
        html_content = render_to_string('emails/sla_reminder.html', context)
        text_content = f"""
        SLA Reminder
        
        Dear {context['staff_name']},
        
        This is a reminder that complaint #{context['complaint_id']} has an SLA deadline of {context['sla_deadline']}.
        
        Days remaining: {context['days_remaining']}
        
        Please ensure timely resolution to avoid SLA breach.
        """
        self._send_email('SLA Reminder - Complaint Resolution', html_content, text_content)

    def _send_sla_second_reminder(self):
        """Example SLA second reminder email (uses template)"""
        context = {
            'staff_name': 'Manager Hassan Al-Balushi',
            'complaint_id': 'COMP-2026-0035',
            'complaint_title': 'Unprofessional Behavior of Staff Member',
            'sla_deadline': 'April 12, 2026',
            'hours_remaining': '24 hours',
        }
        html_content = render_to_string('emails/sla_second_reminder.html', context)
        text_content = f"""
        URGENT SLA REMINDER
        
        Dear {context['staff_name']},
        
        Complaint #{context['complaint_title']} (#COMP-2026-0035) will breach SLA in {context['hours_remaining']}.
        
        Immediate action required!
        """
        self._send_email('URGENT: SLA Breach Imminent', html_content, text_content)

    def _send_complaint_notification_inline(self):
        """Example complaint notification (currently inline - no template)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">Complaint Notification</h1>
        <p style="margin: 0 0 15px; font-size: 16px; color: #1e293b; line-height: 1.6;">Dear Staff Member,</p>
        <p style="margin: 0 0 20px; font-size: 16px; color: #475569; line-height: 1.6;">A new complaint has been logged and requires your attention:</p>
        <div style="background-color: #f8fafc; border-radius: 6px; padding: 20px; margin-bottom: 20px;">
            <p style="margin: 0; font-size: 14px; color: #64748b; line-height: 1.8;">
                <strong style="color: #005696;">Reference:</strong> #COMP-2026-0050<br>
                <strong style="color: #005696;">Title:</strong> Cleanliness Issue in Ward 3B<br>
                <strong style="color: #005696;">Patient:</strong> Mrs. Layla Ahmed<br>
                <strong style="color: #005696;">Department:</strong> Inpatient Ward 3B<br>
                <strong style="color: #005696;">Status:</strong> New
            </p>
        </div>
        <p style="margin: 0; font-size: 14px; color: #475569; line-height: 1.6;">Please review and take appropriate action.</p>
        """
        text_content = """
        Complaint Notification
        
        Dear Staff Member,
        
        A new complaint has been logged and requires your attention:
        
        Reference: #COMP-2026-0050
        Title: Cleanliness Issue in Ward 3B
        Patient: Mrs. Layla Ahmed
        Department: Inpatient Ward 3B
        Status: New
        
        Please review and take appropriate action.
        """
        self._send_email('New Complaint Notification', html_content, text_content)

    def _send_complaint_resolution_inline(self):
        """Example complaint resolution notification (currently inline - no template)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">Complaint Resolved</h1>
        <p style="margin: 0 0 15px; font-size: 16px; color: #1e293b; line-height: 1.6;">Dear Patient,</p>
        <p style="margin: 0 0 20px; font-size: 16px; color: #475569; line-height: 1.6;">Your complaint has been resolved!</p>
        <div style="background-color: #f8fafc; border-radius: 6px; padding: 20px; margin-bottom: 20px;">
            <p style="margin: 0; font-size: 14px; color: #64748b; line-height: 1.8;">
                <strong style="color: #005696;">Reference:</strong> #COMP-2026-0045<br>
                <strong style="color: #005696;">Title:</strong> Appointment Scheduling Issue<br>
                <strong style="color: #005696;">Resolution:</strong> We have improved our scheduling system and scheduled your appointment for next week.
            </p>
        </div>
        <p style="margin: 0; font-size: 14px; color: #475569; line-height: 1.6;">We hope you are satisfied with the resolution. If you have any concerns, please contact us.</p>
        <p style="margin: 10px 0 0; font-size: 14px; color: #475569; line-height: 1.6;">Thank you for your feedback.</p>
        """
        text_content = """
        Complaint Resolved
        
        Dear Patient,
        
        Your complaint has been resolved!
        
        Reference: #COMP-2026-0045
        Title: Appointment Scheduling Issue
        Resolution: We have improved our scheduling system and scheduled your appointment for next week.
        
        We hope you are satisfied with the resolution. If you have any concerns, please contact us.
        
        Thank you for your feedback.
        """
        self._send_email('Your Complaint Has Been Resolved', html_content, text_content)

    def _send_admin_new_complaint_inline(self):
        """Example admin new complaint notification (currently inline - no template)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">🚨 New Complaint Alert</h1>
                    <p>Dear Administrator,</p>
                    <div class="alert-box">
                        <strong>A new high-priority complaint has been logged:</strong><br><br>
                        <strong>Reference:</strong> #COMP-2026-0055<br>
                        <strong>Title:</strong> Medical Error in Medication Administration<br>
                        <strong>Patient:</strong> Mr. Saeed Al-Maktoum<br>
                        <strong>Hospital:</strong> Al Hammadi Hospital - ER<br>
                        <strong>Category:</strong> Patient Safety<br>
                        <strong>Priority:</strong> HIGH<br>
                        <strong>Date:</strong> April 7, 2026
                    </div>
                    <p>Immediate attention required. Please review and assign to appropriate staff.</p>
                
        """
        text_content = """
        🚨 New Complaint Alert
        
        Dear Administrator,
        
        A new high-priority complaint has been logged:
        
        Reference: #COMP-2026-0055
        Title: Medical Error in Medication Administration
        Patient: Mr. Saeed Al-Maktoum
        Hospital: Al Hammadi Hospital - ER
        Category: Patient Safety
        Priority: HIGH
        Date: April 7, 2026
        
        Immediate attention required. Please review and assign to appropriate staff.
        """
        self._send_email('🚨 New High-Priority Complaint', html_content, text_content)

    def _send_escalation_inline(self):
        """Example escalation notification (currently inline - no template)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">⚠️ Complaint Escalated</h1>
                    <p>Dear Manager,</p>
                    <div class="warning-box">
                        <strong>Complaint has been escalated to your attention:</strong><br><br>
                        <strong>Reference:</strong> #COMP-2026-0040<br>
                        <strong>Title:</strong> Repeated Service Failures<br>
                        <strong>Reason:</strong> Multiple unresolved complaints from same patient<br>
                        <strong>Escalated By:</strong> PX Department Head<br>
                        <strong>Date:</strong> April 7, 2026
                    </div>
                    <p>Please review this complaint and provide your intervention to ensure resolution.</p>
                
        """
        text_content = """
        ⚠️ Complaint Escalated
        
        Dear Manager,
        
        Complaint has been escalated to your attention:
        
        Reference: #COMP-2026-0040
        Title: Repeated Service Failures
        Reason: Multiple unresolved complaints from same patient
        Escalated By: PX Department Head
        Date: April 7, 2026
        
        Please review this complaint and provide your intervention to ensure resolution.
        """
        self._send_email('⚠️ Complaint Escalated to Manager', html_content, text_content)

    # ========================================================================
    # OBSERVATIONS EMAILS
    # ========================================================================

    def _send_new_observation(self):
        """Example new observation notification (uses template)"""
        context = {
            'observer_name': 'Quality Inspector Nadia',
            'observation_title': 'Hand Hygiene Compliance Check',
            'observation_category': 'Infection Control',
            'location': 'ICU - Wing A',
            'observation_date': 'April 7, 2026',
            'description': 'Observed good compliance during morning shift. Need improvement in evening shift.',
        }
        html_content = render_to_string('emails/new_observation_notification.html', context)
        text_content = f"""
        New Observation Logged
        
        A new observation has been logged:
        
        Observer: {context['observer_name']}
        Title: {context['observation_title']}
        Category: {context['observation_category']}
        Location: {context['location']}
        Date: {context['observation_date']}
        
        Description: {context['description']}
        """
        self._send_email('New Observation Logged', html_content, text_content)

    def _send_observation_assigned(self):
        """Example observation assigned notification (uses template)"""
        context = {
            'assignee_name': 'Dr. Rania Al-Sayed',
            'observation_title': 'Medication Storage Temperature Logs',
            'assigned_by': 'Quality Manager',
            'due_date': 'April 14, 2026',
        }
        html_content = render_to_string('emails/observation_assigned.html', context)
        text_content = f"""
        Observation Assigned to You
        
        Dear {context['assignee_name']},
        
        You have been assigned to address the following observation:
        
        Title: {context['observation_title']}
        Assigned By: {context['assigned_by']}
        Due Date: {context['due_date']}
        
        Please take appropriate action.
        """
        self._send_email('Observation Assigned to You', html_content, text_content)

    def _send_observation_resolved(self):
        """Example observation resolved notification (uses template)"""
        context = {
            'observation_title': 'Expired Medications in Emergency Cart',
            'resolved_by': 'Pharmacy Supervisor',
            'resolution_date': 'April 7, 2026',
        }
        html_content = render_to_string('emails/observation_resolved.html', context)
        text_content = f"""
        Observation Resolved
        
        The following observation has been resolved:
        
        Title: {context['observation_title']}
        Resolved By: {context['resolved_by']}
        Date: {context['resolution_date']}
        
        Thank you for your prompt action.
        """
        self._send_email('Observation Has Been Resolved', html_content, text_content)

    def _send_observation_sla_reminder(self):
        """Example observation SLA reminder (uses template)"""
        context = {
            'observation_title': 'Patient Identification Band Compliance',
            'sla_deadline': 'April 10, 2026',
            'days_remaining': '3 days',
        }
        html_content = render_to_string('emails/observation_sla_reminder.html', context)
        text_content = f"""
        SLA Reminder: Observation
        
        The following observation is approaching SLA deadline:
        
        Title: {context['observation_title']}
        SLA Deadline: {context['sla_deadline']}
        Days Remaining: {context['days_remaining']}
        
        Please ensure timely resolution.
        """
        self._send_email('SLA Reminder - Observation', html_content, text_content)

    def _send_observation_monthly_followup(self):
        """Example observation monthly followup (uses template)"""
        context = {
            'month': 'March 2026',
            'total_observations': 45,
            'resolved_count': 38,
            'pending_count': 7,
            'resolution_rate': '84%',
        }
        html_content = render_to_string('emails/observation_monthly_followup.html', context)
        text_content = f"""
        Monthly Observation Summary - {context['month']}
        
        Total Observations: {context['total_observations']}
        Resolved: {context['resolved_count']}
        Pending: {context['pending_count']}
        Resolution Rate: {context['resolution_rate']}
        
        Please review and address pending observations.
        """
        self._send_email(f'Monthly Observation Summary - {context["month"]}', html_content, text_content)

    # ========================================================================
    # ANALYTICS EMAILS
    # ========================================================================

    def _send_px_digest(self):
        """Example PX digest weekly report (uses template)"""
        context = {
            'period': 'April 1-7, 2026',
            'total_complaints': 23,
            'resolved_complaints': 18,
            'pending_complaints': 5,
            'resolution_rate': '78%',
            'total_observations': 12,
            'total_surveys': 156,
            'satisfaction_score': '4.2/5',
            'top_categories': ['Wait Time', 'Staff Behavior', 'Facility Cleanliness'],
        }
        html_content = render_to_string('emails/px_digest_weekly.html', context)
        text_content = f"""
        Weekly PX Digest - {context['period']}
        
        Complaints Summary:
        - Total: {context['total_complaints']}
        - Resolved: {context['resolved_complaints']}
        - Pending: {context['pending_complaints']}
        - Resolution Rate: {context['resolution_rate']}
        
        Observations: {context['total_observations']}
        Surveys Completed: {context['total_surveys']}
        Satisfaction Score: {context['satisfaction_score']}
        
        Top Complaint Categories:
        {', '.join(context['top_categories'])}
        """
        self._send_email(f'Weekly PX Digest - {context["period"]}', html_content, text_content)

    # ========================================================================
    # SURVEYS EMAILS
    # ========================================================================

    def _send_survey_invitation(self):
        """Example survey invitation (currently inline - no HTML template)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">Share Your Experience</h1>
                    <p>Dear Valued Patient,</p>
                    <p>Thank you for visiting Al Hammadi Hospital. We would appreciate your feedback to help us improve our services.</p>
                    <p>Please take a few minutes to complete our satisfaction survey:</p>
                    <p style="text-align: center; margin: 30px 0;">
                        <a href="https://px360.sa/survey/complete/abc123" class="button">Take Survey</a>
                    </p>
                    <p>Your feedback is important to us!</p>
                
        """
        text_content = """
        Share Your Experience
        
        Dear Valued Patient,
        
        Thank you for visiting Al Hammadi Hospital. We would appreciate your feedback to help us improve our services.
        
        Please take a few minutes to complete our satisfaction survey:
        https://px360.sa/survey/complete/abc123
        
        Your feedback is important to us!
        """
        self._send_email('Share Your Experience - Patient Satisfaction Survey', html_content, text_content)

    def _send_survey_invitation_template(self):
        """Example survey invitation using existing template (not currently used)"""
        context = {
            'patient_name': 'Mrs. Noor Al-Hashimi',
            'survey_url': 'https://px360.sa/survey/complete/xyz789',
            'hospital_name': 'Al Hammadi Hospital',
        }
        html_content = render_to_string('emails/survey_invitation.html', context)
        text_content = f"""
        Share Your Experience
        
        Dear {context['patient_name']},
        
        Thank you for visiting {context['hospital_name']}. We would appreciate your feedback.
        
        Complete our survey here: {context['survey_url']}
        
        Your feedback is important to us!
        """
        self._send_email('Patient Satisfaction Survey - Your Feedback Matters', html_content, text_content)

    # ========================================================================
    # APPRECIATION EMAILS
    # ========================================================================

    def _send_appreciation_notification(self):
        """Example appreciation notification (currently inline - no template)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">🌟 Staff Appreciation</h1>
                    <p>Dear Team,</p>
                    <div class="appreciation-box">
                        <strong>Excellent work recognized!</strong><br><br>
                        <strong>Staff Member:</strong> Nurse Amira Hassan<br>
                        <strong>Department:</strong> Emergency Department<br>
                        <strong>Appreciation:</strong> Outstanding patient care during emergency situation<br>
                        <strong>From:</strong> Patient Family Member
                    </div>
                    <p>Congratulations on this recognition! Your dedication to patient care is truly appreciated.</p>
                
        """
        text_content = """
        🌟 Staff Appreciation
        
        Dear Team,
        
        Excellent work recognized!
        
        Staff Member: Nurse Amira Hassan
        Department: Emergency Department
        Appreciation: Outstanding patient care during emergency situation
        From: Patient Family Member
        
        Congratulations on this recognition! Your dedication to patient care is truly appreciated.
        """
        self._send_email('🌟 Staff Appreciation Recognition', html_content, text_content)

    # ========================================================================
    # CORE / PUBLIC EMAILS
    # ========================================================================

    def _send_public_inquiry(self):
        """Example public inquiry notification (uses template)"""
        context = {
            'inquiry_id': 'INQ-2026-0089',
            'sender_name': 'Mr. Abdulrahman Al-Farsi',
            'sender_email': 'abdulrahman@example.com',
            'subject': 'Question about Insurance Coverage',
            'message': 'I would like to know if my insurance covers laboratory tests and specialist consultations. My insurance provider is Bupa Arabia.',
            'submitted_date': 'April 7, 2026',
        }
        html_content = render_to_string('emails/public_inquiry_notification.html', context)
        text_content = f"""
        New Public Inquiry
        
        Inquiry ID: {context['inquiry_id']}
        Sender: {context['sender_name']} ({context['sender_email']})
        Subject: {context['subject']}
        Date: {context['submitted_date']}
        
        Message:
        {context['message']}
        
        Please respond to this inquiry at your earliest convenience.
        """
        self._send_email('New Public Inquiry Received', html_content, text_content)

    # ========================================================================
    # NOTIFICATION SETTINGS SERVICE EMAILS (Currently Inline)
    # ========================================================================

    def _send_explanation_requested(self):
        """Example explanation requested from settings service (currently inline)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">Explanation Requested</h1>
                    <p>Dear Staff Member,</p>
                    <p>An explanation has been requested for complaint #COMP-2026-0060.</p>
                    <p><strong>Deadline:</strong> April 14, 2026</p>
                    <p>Please submit your explanation through the system.</p>
                
        """
        text_content = """
        Explanation Requested
        
        Dear Staff Member,
        
        An explanation has been requested for complaint #COMP-2026-0060.
        
        Deadline: April 14, 2026
        
        Please submit your explanation through the system.
        """
        self._send_email('Explanation Requested for Complaint', html_content, text_content)

    def _send_complaint_assigned(self):
        """Example complaint assigned from settings service (currently inline)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">Complaint Assigned to You</h1>
                    <p>Dear Dr. Khalid,</p>
                    <p>A complaint has been assigned to you for review and response.</p>
                    <p><strong>Complaint:</strong> #COMP-2026-0062 - Staff Attitude Issue</p>
                    <p><strong>Department:</strong> Outpatient Clinic</p>
                    <p>Please review and provide your explanation.</p>
                
        """
        text_content = """
        Complaint Assigned to You
        
        Dear Dr. Khalid,
        
        A complaint has been assigned to you for review and response.
        
        Complaint: #COMP-2026-0062 - Staff Attitude Issue
        Department: Outpatient Clinic
        
        Please review and provide your explanation.
        """
        self._send_email('Complaint Assigned to You', html_content, text_content)

    def _send_complaint_status_changed(self):
        """Example complaint status changed from settings service (currently inline)"""
        html_content = f"""
        <h1 style="margin: 0 0 20px; font-size: 24px; font-weight: 600; color: #005696;">Complaint Status Updated</h1>
                    <p>Dear Stakeholder,</p>
                    <p>The status of complaint #COMP-2026-0058 has been updated.</p>
                    <p><strong>Previous Status:</strong> Under Review</p>
                    <p><strong>New Status:</strong> Resolved</p>
                    <p><strong>Resolution:</strong> Issue has been addressed with staff member. Apology issued to patient.</p>
                
        """
        text_content = """
        Complaint Status Updated
        
        Dear Stakeholder,
        
        The status of complaint #COMP-2026-0058 has been updated.
        
        Previous Status: Under Review
        New Status: Resolved
        Resolution: Issue has been addressed with staff member. Apology issued to patient.
        """
        self._send_email('Complaint Status Updated', html_content, text_content)
