from datetime import date, timedelta

from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand

from api.models import (
    Branch,
    Brand,
    GalleryImage,
    Inventory,
    InventoryStatus,
    Offer,
    Part,
    Scooter,
    ScooterAsset3D,
    Testimonial,
)


class Command(BaseCommand):
    help = "Seed Bashista Auto demo data for the Django DRF backend."

    def handle(self, *args, **options):
        user_model = get_user_model()
        admin, created = user_model.objects.get_or_create(
            username="admin",
            defaults={
                "email": "admin@bashistaauto.com",
                "is_staff": True,
                "is_superuser": True,
            },
        )
        admin.email = "admin@bashistaauto.com"
        admin.is_staff = True
        admin.is_superuser = True
        admin.set_password("Admin@12345")
        admin.save()
        self.stdout.write(self.style.SUCCESS(f"{'Created' if created else 'Updated'} admin user admin@bashistaauto.com"))

        brands = [
            ("Ampere", "ampere", "Reliable city EV scooters", "Comfort-first electric mobility"),
            ("Ather", "ather", "Smart premium scooters", "Connected performance"),
            ("TVS iQube", "tvs-iqube", "Trusted electric scooters", "Service network and practicality"),
            ("Ola Electric", "ola-electric", "Feature-rich EV scooters", "Long range and modern tech"),
            ("NIU", "niu", "Urban smart mobility", "Compact connected scooters"),
            ("Yadea", "yadea", "Global EV scooter brand", "Efficient everyday riding"),
        ]
        brand_map = {}
        for name, slug, description, strength in brands:
            brand, _ = Brand.objects.update_or_create(
                slug=slug,
                defaults={
                    "name": name,
                    "short_description": description,
                    "logo_text": name[:3].upper(),
                    "key_strength": strength,
                    "popular_models": [],
                    "is_featured": True,
                },
            )
            brand_map[slug] = brand

        branches = [
            {
                "name": "Bashista Auto - Bharatpur",
                "slug": "bharatpur-chitwan",
                "type": "Main Branch",
                "city": "Bharatpur",
                "district": "Chitwan",
                "phone": "+9779709046762",
                "whatsapp": "+9779709046762",
            },
            {
                "name": "Bashista Auto - Kawasoti",
                "slug": "kawasoti-nawalpur",
                "type": "Branch",
                "city": "Kawasoti",
                "district": "Nawalpur",
                "phone": "+9779709046761",
                "whatsapp": "+9779709046761",
            },
        ]
        branch_map = {}
        for item in branches:
            branch, _ = Branch.objects.update_or_create(
                slug=item["slug"],
                defaults={
                    **item,
                    "opening_hours": "Sun-Fri: 10:00 AM - 6:30 PM",
                    "map_link": "https://maps.google.com",
                },
            )
            branch_map[item["slug"]] = branch

        scooters = [
            ("Ampere Magnus EX", "ampere-magnus-ex", "ampere", 289000, 269000, 100, 50, "6-7 hours"),
            ("Ampere Nexus", "ampere-nexus", "ampere", 399000, 379000, 136, 93, "3.5 hours"),
            ("Ather 450X", "ather-450x", "ather", 455000, 439000, 111, 90, "5.4 hours"),
            ("Ather Rizta", "ather-rizta", "ather", 389000, 369000, 123, 80, "6 hours"),
            ("TVS iQube S", "tvs-iqube-s", "tvs-iqube", 410000, 389000, 100, 78, "4.5 hours"),
            ("Ola S1 Pro", "ola-s1-pro", "ola-electric", 430000, 409000, 195, 120, "6.5 hours"),
        ]
        scooter_map = {}
        for name, slug, brand_slug, price, offer_price, range_km, speed, charging in scooters:
            scooter, _ = Scooter.objects.update_or_create(
                slug=slug,
                defaults={
                    "brand": brand_map[brand_slug],
                    "name": name,
                    "short_description": f"{name} electric scooter available at Bashista Auto.",
                    "long_description": f"{name} is a practical electric scooter for daily rides, test rides, and EV ownership support from Bashista Auto.",
                    "price": price,
                    "offer_price": offer_price,
                    "range_km": range_km,
                    "top_speed_kmph": speed,
                    "charging_time": charging,
                    "battery": "Lithium-ion battery",
                    "motor_power": "Electric hub motor",
                    "warranty": "3 years battery warranty",
                    "colors": ["White", "Blue", "Black"],
                    "ar_enabled": False,
                    "is_featured": True,
                    "published": True,
                    "specs": [
                        {"label": "Range", "value": f"{range_km} km"},
                        {"label": "Top Speed", "value": f"{speed} km/h"},
                        {"label": "Charging", "value": charging},
                    ],
                },
            )
            scooter_map[slug] = scooter
            ScooterAsset3D.objects.get_or_create(scooter=scooter)

        for scooter in scooter_map.values():
            Inventory.objects.update_or_create(
                scooter=scooter,
                branch=branch_map["bharatpur-chitwan"],
                defaults={"status": InventoryStatus.IN_STOCK, "quantity": 4, "test_ride_available": True},
            )
            Inventory.objects.update_or_create(
                scooter=scooter,
                branch=branch_map["kawasoti-nawalpur"],
                defaults={"status": InventoryStatus.LIMITED_STOCK, "quantity": 1, "test_ride_available": True},
            )

        for name, category, price in [
            ("Lithium Battery Pack", "Batteries", 68000),
            ("Portable EV Charger", "Chargers", 14500),
            ("Tubeless Scooter Tyre", "Tyres", 4200),
            ("Front Brake Pads", "Brake Pads", 1800),
            ("LED Headlight Assembly", "Lights", 6500),
            ("Riding Helmet", "Helmets", 3500),
        ]:
            Part.objects.update_or_create(
                name=name,
                defaults={
                    "category": category,
                    "price": price,
                    "compatibility": ["Universal"],
                    "inquiry_only": False,
                    "stock_status": InventoryStatus.IN_STOCK,
                },
            )

        valid_until = date.today() + timedelta(days=45)
        for scooter in list(scooter_map.values())[:4]:
            Offer.objects.update_or_create(
                title=f"{scooter.name} Cashback Offer",
                defaults={
                    "category": "Cashback Offers",
                    "description": f"Limited-period cashback and finance benefits on {scooter.name}.",
                    "discount_label": "Rs. 20,000 off",
                    "valid_until": valid_until,
                    "active": True,
                    "scooter": scooter,
                    "brand": scooter.brand,
                    "branch": branch_map["bharatpur-chitwan"],
                },
            )

        for title, category in [
            ("Bharatpur Showroom", "Showroom"),
            ("Kawasoti Branch", "Branches"),
            ("Product Display", "Products"),
            ("Happy Delivery", "Deliveries"),
        ]:
            GalleryImage.objects.get_or_create(title=title, defaults={"category": category, "alt": title, "featured": True})

        Testimonial.objects.update_or_create(
            customer_name="Suman Adhikari",
            defaults={
                "location": "Bharatpur",
                "rating": 5,
                "comment": "Helpful team, clear guidance, and a smooth electric scooter buying experience.",
                "scooter_name": "Ather 450X",
            },
        )

        self.stdout.write(self.style.SUCCESS("Bashista Auto Django data seeded."))
