from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.db import transaction
from datetime import timedelta
import random

from apps.complaints.models import Complaint, Inquiry, ComplaintCategory
from apps.organizations.models import Hospital, Department

User = get_user_model()


class Command(BaseCommand):
    help = 'Creates 3 admin users (rahaf, abrar, amaal) and assigns multiple complaints and inquiries to each'

    def add_arguments(self, parser):
        parser.add_argument(
            '--complaints-per-user',
            type=int,
            default=5,
            help='Number of complaints to create per user (default: 5)'
        )
        parser.add_argument(
            '--inquiries-per-user',
            type=int,
            default=5,
            help='Number of inquiries to create per user (default: 5)'
        )

    def handle(self, *args, **options):
        complaints_per_user = options['complaints_per_user']
        inquiries_per_user = options['inquiries_per_user']

        self.stdout.write(self.style.SUCCESS('Starting to seed admin test data...'))

        # Get or create default hospital and department
        hospital = self.get_default_hospital()
        department = self.get_default_department(hospital)

        # Create admin users
        admin_users = self.create_admin_users()

        if not admin_users:
            self.stdout.write(self.style.ERROR('No admin users were created. Exiting.'))
            return

        # Get available categories
        categories = list(ComplaintCategory.objects.filter(level=4)[:10])

        if not categories:
            self.stdout.write(self.style.WARNING('No categories found. Creating some default categories...'))
            categories = self.create_default_categories()

        # Create complaints and inquiries for each admin user
        for user in admin_users:
            self.stdout.write(f'\nCreating data for user: {user.get_full_name()}')

            # Create complaints
            self.create_complaints_for_user(
                user, 
                hospital, 
                department, 
                categories, 
                complaints_per_user
            )

            # Create inquiries
            self.create_inquiries_for_user(
                user, 
                hospital, 
                department, 
                categories, 
                inquiries_per_user
            )

        self.stdout.write(self.style.SUCCESS('\n✓ Admin test data seeding completed successfully!'))
        self.stdout.write(f'\nSummary:')
        self.stdout.write(f'  - Admin users created: {len(admin_users)}')
        self.stdout.write(f'  - Total complaints: {len(admin_users) * complaints_per_user}')
        self.stdout.write(f'  - Total inquiries: {len(admin_users) * inquiries_per_user}')

    def get_default_hospital(self):
        """Get or create a default hospital"""
        hospital, created = Hospital.objects.get_or_create(
            name="Al Hammadi Hospital - Riyadh",
            defaults={
                'code': 'HAM-RIY',
                'city': 'Riyadh',
                'address': 'Olaya Street, Riyadh',
                'phone': '+966 11 123 4567',
                'email': 'riyadh@alhammadi.com',
                'status': 'active'
            }
        )
        if created:
            self.stdout.write(f'Created hospital: {hospital.name}')
        return hospital

    def get_default_department(self, hospital):
        """Get or create a default department"""
        department, created = Department.objects.get_or_create(
            name="Patient Services",
            hospital=hospital,
            defaults={
                'code': 'PS',
                'status': 'active'
            }
        )
        if created:
            self.stdout.write(f'Created department: {department.name}')
        return department

    def create_admin_users(self):
        """Create 3 admin users: rahaf, abrar, amaal"""
        users_data = [
            {
                'username': 'rahaf',
                'email': 'rahaf@example.com',
                'first_name': 'Rahaf',
                'last_name': 'Al Saud',
                'is_staff': True,
                'is_superuser': False,
                'is_active': True
            },
            {
                'username': 'abrar',
                'email': 'abrar@example.com',
                'first_name': 'Abrar',
                'last_name': 'Al Qahtani',
                'is_staff': True,
                'is_superuser': False,
                'is_active': True
            },
            {
                'username': 'amaal',
                'email': 'amaal@example.com',
                'first_name': 'Amaal',
                'last_name': 'Al Otaibi',
                'is_staff': True,
                'is_superuser': False,
                'is_active': True
            }
        ]

        users = []
        for user_data in users_data:
            user, created = User.objects.get_or_create(
                username=user_data['username'],
                defaults=user_data
            )
            
            if created:
                user.set_password('password123')  # Set default password
                user.save()
                self.stdout.write(f'Created admin user: {user.get_full_name()}')
            else:
                self.stdout.write(f'Admin user already exists: {user.get_full_name()}')
            
            users.append(user)

        return users

    def create_default_categories(self):
        """Create some default complaint categories"""
        categories = []
        category_names = [
            ('Service Quality', 'Staff Behavior', 'Nurse Attitude', 'Professionalism'),
            ('Service Quality', 'Staff Behavior', 'Doctor Attitude', 'Communication'),
            ('Facilities', 'Cleanliness', 'Room', 'General Cleanliness'),
            ('Process', 'Waiting Time', 'Outpatient', 'Initial Consultation'),
            ('Process', 'Billing', 'Payment', 'Insurance Coverage'),
            ('Medical Care', 'Treatment', 'Medication', 'Wrong Medication'),
            ('Medical Care', 'Diagnosis', 'Tests', 'Delayed Results'),
            ('Food Service', 'Patient Meals', 'Quality', 'Taste'),
            ('Food Service', 'Patient Meals', 'Timing', 'Late Delivery'),
            ('Communication', 'Information', 'Discharge', 'Instructions')
        ]

        for domain, category, subcategory, name in category_names:
            cat, created = ComplaintCategory.objects.get_or_create(
                name=name,
                defaults={
                    'domain': domain,
                    'category': category,
                    'subcategory': subcategory,
                    'level': 4,
                    'is_active': True
                }
            )
            if created:
                categories.append(cat)
                self.stdout.write(f'Created category: {name}')
            else:
                categories.append(cat)

        return categories

    def create_complaints_for_user(self, user, hospital, department, categories, count):
        """Create complaints assigned to the user"""
        statuses = ['open', 'in_progress', 'resolved', 'closed']
        severities = ['low', 'medium', 'high', 'critical']
        
        complaint_titles = [
            'Poor staff attitude during my visit',
            'Long waiting time at the reception',
            'Billing issues with insurance claim',
            'Room cleanliness needs improvement',
            'Doctor was dismissive of my concerns',
            'Medication provided was incorrect',
            'Food quality was unacceptable',
            'Nurse was rude and unhelpful',
            'Facilities were not well maintained',
            'Discharge instructions were unclear',
            'Lost my personal belongings',
            'Emergency response was too slow',
            'Parking facilities are inadequate',
            'Appointment scheduling was chaotic',
            'Staff did not follow proper procedures',
            'Privacy was not respected',
            'Equipment appeared old and malfunctioning',
            'Communication between departments was poor',
            'Follow-up care was not arranged',
            'Overall experience was disappointing'
        ]

        created_count = 0
        for i in range(count):
            # Select random category if available
            category = random.choice(categories) if categories else None
            
            # Randomize date within last 90 days
            days_ago = random.randint(0, 90)
            created_date = timezone.now() - timedelta(days=days_ago)
            
            # Randomize due date (some overdue, some not)
            if random.random() < 0.3:  # 30% chance of being overdue
                due_date = created_date + timedelta(days=random.randint(1, 7))
            else:
                due_date = created_date + timedelta(days=random.randint(7, 30))

            complaint = Complaint.objects.create(
                title=random.choice(complaint_titles),
                description=f"This is a test complaint created for {user.get_full_name()}. "
                           f"It was created on {created_date.strftime('%Y-%m-%d')} "
                           f"with {random.choice(severities).upper()} severity.",
                hospital=hospital,
                department=department,
                severity=random.choice(severities),
                status=random.choice(statuses),
                assigned_to=user,
                created_at=created_date,
                updated_at=created_date + timedelta(days=random.randint(0, days_ago)),
                due_at=due_date,
                contact_name=f'Patient {random.randint(1000, 9999)}',
                contact_phone=f'05{random.randint(0, 9)}{random.randint(1000000, 9999999)}',
                contact_email=f'patient{random.randint(100, 999)}@example.com'
            )
            
            created_count += 1
            self.stdout.write(f'  Created complaint #{complaint.id}: {complaint.title[:50]}...')

        return created_count

    def create_inquiries_for_user(self, user, hospital, department, categories, count):
        """Create inquiries assigned to the user"""
        statuses = ['open', 'in_progress', 'resolved', 'closed']
        severities = ['low', 'medium', 'high']
        
        inquiry_titles = [
            'Question about appointment booking',
            'Inquiry about insurance coverage',
            'Request for medical records',
            'Information about hospital services',
            'Question about doctor availability',
            'Inquiry about test results',
            'Request for price list',
            'Question about visiting hours',
            'Inquiry about specialized treatment',
            'Request for second opinion',
            'Question about discharge process',
            'Inquiry about medication side effects',
            'Request for dietary information',
            'Question about transportation',
            'Inquiry about follow-up appointments',
            'Request for accommodation',
            'Question about emergency procedures',
            'Inquiry about patient rights',
            'Request for feedback form',
            'Question about hospital policies',
            'Inquiry about international patient services'
        ]

        created_count = 0
        for i in range(count):
            # Select random category if available
            category = random.choice(categories) if categories else None
            
            # Randomize date within last 90 days
            days_ago = random.randint(0, 90)
            created_date = timezone.now() - timedelta(days=days_ago)
            
            # Randomize due date (some overdue, some not)
            if random.random() < 0.3:  # 30% chance of being overdue
                due_date = created_date + timedelta(days=random.randint(1, 7))
            else:
                due_date = created_date + timedelta(days=random.randint(7, 30))

            inquiry = Inquiry.objects.create(
                subject=random.choice(inquiry_titles),
                message=f"This is a test inquiry created for {user.get_full_name()}. "
                       f"It was created on {created_date.strftime('%Y-%m-%d')} "
                       f"with {random.choice(severities).upper()} severity.",
                hospital=hospital,
                department=department,
                category=random.choice(['appointment', 'billing', 'medical_records', 'general', 'other']),
                status=random.choice(statuses),
                assigned_to=user,
                created_at=created_date,
                updated_at=created_date + timedelta(days=random.randint(0, days_ago)),
                contact_name=f'Patient {random.randint(1000, 9999)}',
                contact_phone=f'05{random.randint(0, 9)}{random.randint(1000000, 9999999)}',
            )
            
            created_count += 1
            self.stdout.write(f'  Created inquiry #{inquiry.id}: {inquiry.subject[:50]}...')

        return created_count