"""
Seed data for events app.
"""
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.utils import timezone
from datetime import timedelta
from apps.events.models import Event, EventTemplate, EventInvitation

User = get_user_model()


class Command(BaseCommand):
    help = "Seed database with sample events"

    def handle(self, *args, **options):
        # Get or create a demo user
        user, created = User.objects.get_or_create(
            email="nurojilukmansyah@gmail.com"
        )
        if created:
            user.set_password("B6585esp__")
            user.save()
            self.stdout.write(f"Created user: {user.email}")

        # Sample events data
        now = timezone.now()
        events_data = [
            {
                "name": "Annual Health Conference 2026",
                "event_type": "conference",
                "description": "Annual conference covering the latest developments in healthcare technology and policy. Join us for keynotes from industry leaders, panel discussions on emerging trends, and networking opportunities with over 500 healthcare professionals.",
                "start_date": now + timedelta(days=30),
                "end_date": now + timedelta(days=32),
                "location": "Jakarta Convention Center, Jl. Jend. Gatot Subroto, Jakarta",
                "status": "published",
                "capacity": 500,
                "tags": ["#healthcare", "#conference", "#annual"],
            },
            {
                "name": "Digital Health Workshop",
                "event_type": "workshop",
                "description": "Hands-on workshop on implementing digital health solutions in clinical settings. Learn from experts about EHR integration, telemedicine platforms, and data analytics.",
                "start_date": now + timedelta(days=14),
                "end_date": now + timedelta(days=14, hours=6),
                "location": "PT Teknologi Nusantara Office, Jakarta",
                "status": "published",
                "capacity": 50,
                "tags": ["#workshop", "#digital-health", "#training"],
            },
            {
                "name": "Telemedicine Best Practices Webinar",
                "event_type": "webinar",
                "description": "Online session discussing telemedicine implementation and best practices. Perfect for healthcare administrators looking to scale virtual care services.",
                "start_date": now + timedelta(days=7),
                "end_date": now + timedelta(days=7, hours=2),
                "location": "Online (Zoom)",
                "status": "published",
                "capacity": 100,
                "tags": ["#webinar", "#telemedicine", "#online"],
            },
            {
                "name": "Healthcare Data Security Seminar",
                "event_type": "seminar",
                "description": "Seminar on protecting patient data and complying with healthcare regulations including UU PDP and international standards.",
                "start_date": now + timedelta(days=21),
                "end_date": now + timedelta(days=21, hours=4),
                "location": "Hotel Indonesia Kempinski, Jakarta",
                "status": "draft",
                "capacity": 150,
                "tags": ["#seminar", "#data-security", "#compliance"],
            },
            {
                "name": "Community Health Dissemination",
                "event_type": "dissemination",
                "description": "Community outreach event to disseminate health information and resources. Free health screenings and educational materials available.",
                "start_date": now + timedelta(days=10),
                "end_date": now + timedelta(days=10, hours=5),
                "location": "Balikpapan Community Center, Kalimantan Timur",
                "status": "published",
                "capacity": 200,
                "tags": ["#dissemination", "#community", "#outreach"],
            },
            {
                "name": "Quarterly Review Meeting",
                "event_type": "meeting",
                "description": "Internal quarterly review meeting for project teams to discuss progress, challenges, and Q3 planning.",
                "start_date": now + timedelta(days=5),
                "end_date": now + timedelta(days=5, hours=3),
                "location": "PT Teknologi Nusantara HQ, Jakarta",
                "status": "completed",
                "capacity": 30,
                "tags": ["#meeting", "#internal", "#review"],
            },
        ]

        templates_data = [
            {
                "name": "Standard Webinar",
                "event_type": "webinar",
                "description": "Standard template for webinar events",
                "duration_hours": 2,
                "default_settings": {"platform": "zoom", "recording": True},
            },
            {
                "name": "Full-Day Conference",
                "event_type": "conference",
                "description": "Standard template for full-day conference events",
                "duration_hours": 8,
                "default_settings": {"platform": "in-person", "catering": True, "certificates": True},
            },
            {
                "name": "Training Workshop",
                "event_type": "workshop",
                "description": "Standard template for training workshops",
                "duration_hours": 6,
                "default_settings": {"platform": "hybrid", "materials": True, "certificates": True},
            },
        ]

        invitations_data = [
            {"name": "Sarah Johnson", "email": "sarah.johnson@apex.com", "status": "accepted"},
            {"name": "Marcus Lee", "email": "marcus.lee@nexacore.com", "status": "accepted"},
            {"name": "Priya Sharma", "email": "priya.sharma@bluewave.com", "status": "pending"},
            {"name": "Daniel Cruz", "email": "daniel.cruz@apex.com", "status": "pending"},
            {"name": "Ingrid Hoffmann", "email": "ingrid.h@nexacore.com", "status": "declined"},
            {"name": "James Okafor", "email": "j.okafor@worldbank.org", "status": "accepted"},
            {"name": "Mei Lin", "email": "mei.lin@adb.org", "status": "pending"},
            {"name": "Ahmad Fauzi", "email": "ahmad.fauzi@kemenko.go.id", "status": "accepted"},
        ]

        for i, event_data in enumerate(events_data):
            event, created = Event.objects.get_or_create(
                name=event_data["name"],
                defaults={
                    "event_type": event_data["event_type"],
                    "description": event_data["description"],
                    "start_date": event_data["start_date"],
                    "end_date": event_data["end_date"],
                    "location": event_data["location"],
                    "organizer": user,
                    "status": event_data["status"],
                    "capacity": event_data["capacity"],
                    "tags": event_data["tags"],
                }
            )

            if created:
                self.stdout.write(f"Created event: {event.name}")
            else:
                self.stdout.write(f"Event already exists: {event.name}")

            # Always add invitations for this event
            EventInvitation.objects.filter(event=event).delete()

            for inv_data in invitations_data:
                EventInvitation.objects.create(
                    event=event,
                    invited_by=user,
                    name=inv_data["name"],
                    email=inv_data["email"],
                    status=inv_data["status"],
                )

            self.stdout.write(f"  Added {len(invitations_data)} invitations")

        for template_data in templates_data:
            template, created = EventTemplate.objects.get_or_create(
                name=template_data["name"],
                defaults={
                    "event_type": template_data["event_type"],
                    "description": template_data["description"],
                    "duration_hours": template_data["duration_hours"],
                    "default_settings": template_data["default_settings"],
                    "created_by": user,
                }
            )

            if created:
                self.stdout.write(f"Created template: {template.name}")
            else:
                self.stdout.write(f"Template already exists: {template.name}")

        self.stdout.write(self.style.SUCCESS("Successfully seeded events data"))
