from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.db import transaction
from apps.customers.models import Customer
from faker import Faker
import random
from datetime import date, timedelta


class Command(BaseCommand):
    help = (
        "Creates multiple customers (5 by default) with their associated user accounts."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--count",
            type=int,
            default=5,
            help="Number of customers to create (default: 5)",
        )
        parser.add_argument(
            "--admin-user",
            type=str,
            default="admin@example.com",
            help="Email of admin user to set as creator (default: admin@example.com)",
        )

    def handle(self, *args, **options):
        User = get_user_model()
        fake = Faker("fr_FR")  # Utilisation du français
        count = options["count"]
        admin_email = options["admin_user"]

        self.stdout.write(self.style.SUCCESS(f"--- Creating {count} Customers ---"))

        # Get admin user for created_by field
        try:
            admin_user = User.objects.get(email=admin_email)
        except User.DoesNotExist:
            self.stdout.write(
                self.style.WARNING(
                    f"Admin user {admin_email} not found. Using None for created_by."
                )
            )
            admin_user = None

        created_customers = []

        with transaction.atomic():
            # Get the current highest client number to avoid conflicts
            existing_client_emails = User.objects.filter(
                email__regex=r"^client\d+@amifond\.com$"
            ).values_list("email", flat=True)

            # Extract numbers from existing emails
            existing_numbers = []
            for email in existing_client_emails:
                try:
                    num = int(email.split("@")[0].replace("client", ""))
                    existing_numbers.append(num)
                except (ValueError, IndexError):
                    continue

            # Start from the highest existing number + 1
            start_num = max(existing_numbers) + 1 if existing_numbers else 1

            for i in range(start_num, start_num + count):
                # Generate user data
                first_name = fake.first_name()
                last_name = fake.last_name()
                email = f"client{i}@amifond.com"
                username = f"client{i}"

                # Double-check if user already exists (safety check)
                if User.objects.filter(email=email).exists():
                    self.stdout.write(
                        self.style.WARNING(
                            f"User with email {email} already exists. Skipping..."
                        )
                    )
                    continue

                # Create user
                user = User.objects.create_user(
                    email=email,
                    username=username,
                    first_name=first_name,
                    last_name=last_name,
                    password="defaultpassword123",  # Mot de passe par défaut
                )

                # Generate customer data
                customer_data = {
                    "user": user,
                    "address": fake.address(),
                    "id_card_number": f"ID{fake.random_int(min=100000000, max=999999999)}",
                    "phone_number": fake.phone_number(),
                    "birth_date": fake.date_of_birth(minimum_age=18, maximum_age=80),
                    "created_by": admin_user,
                }

                # Create customer
                customer = Customer.objects.create(**customer_data)
                created_customers.append(customer)

                self.stdout.write(
                    self.style.SUCCESS(
                        f"✓ Created customer {i}: {first_name} {last_name} ({email})"
                    )
                )

        # Summary
        self.stdout.write(self.style.SUCCESS("\n--- Summary ---"))
        self.stdout.write(f"Successfully created {len(created_customers)} customers:")

        for customer in created_customers:
            self.stdout.write(
                f"  • {customer.user.first_name} {customer.user.last_name} "
                f"({customer.user.email}) - ID: {customer.id}"
            )

        if created_customers:
            self.stdout.write(self.style.SUCCESS("\n--- Login Information ---"))
            self.stdout.write(
                "Default password for all created users: defaultpassword123"
            )
            self.stdout.write("Users can log in with their email and this password.")

        self.stdout.write(self.style.SUCCESS("\n--- Customer Creation Complete ---"))

    def _generate_realistic_data(self, fake, index):
        """Generate more realistic customer data."""
        # Some realistic French addresses and data
        addresses = [
            "12 Rue de la République, 75011 Paris",
            "45 Avenue des Champs-Élysées, 75008 Paris",
            "23 Rue Victor Hugo, 69002 Lyon",
            "78 Boulevard de la Liberté, 59000 Lille",
            "34 Place de la Comédie, 34000 Montpellier",
        ]

        return {
            "address": addresses[index % len(addresses)],
            "phone_number": fake.phone_number(),
            "birth_date": fake.date_of_birth(minimum_age=25, maximum_age=65),
        }
