from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from store.models import Category, Product, Coupon
from django.utils import timezone
from datetime import timedelta


class Command(BaseCommand):
    help = 'Seed the database with demo data'

    def handle(self, *args, **kwargs):
        self.stdout.write('🌱 Seeding demo data...')

        # Categories
        cats_data = [
            ("Men's Wear",     'men',         0),
            ("Women's Wear",   'women',       1),
            ('Shoes',          'shoes',       2),
            ('Bags',           'bags',        3),
            ('Watches',        'watches',     4),
            ('Accessories',    'accessories', 5),
            ('Traditional Wear','traditional',6),
            ('Sportswear',     'sportswear',  7),
        ]

        categories = {}
        for name, slug, order in cats_data:
            cat, created = Category.objects.get_or_create(
                slug=slug,
                defaults={'name': name, 'order': order, 'is_active': True}
            )
            categories[slug] = cat
            if created:
                self.stdout.write(f'  ✓ Category: {name}')

        # Products
        products_data = [
            ('Classic Oxford Shirt',      'men',         8500,  6500,  'A timeless Oxford shirt crafted from premium cotton blend. Perfect for office and casual outings.',              'S,M,L,XL,XXL',         'White,Blue,Black,Grey',          50, True,  True,  True),
            ('Slim Fit Chinos',           'men',         12000, None,  'Versatile slim-fit chino trousers in a comfortable stretch fabric.',                                            'S,M,L,XL,XXL',         'Khaki,Navy,Olive,Black',         30, True,  False, True),
            ('Agbada Traditional Set',    'traditional', 35000, 28000, 'Stunning hand-embroidered Agbada set for special occasions. Includes top, inner wear and trousers.',            'S,M,L,XL,XXL',         'Gold,Blue,White,Red',            15, True,  True,  False),
            ('Sports Running Shorts',     'sportswear',  4500,  None,  'Lightweight moisture-wicking running shorts with an inner liner and zip pocket.',                              'S,M,L,XL',             'Black,Navy,Grey',                80, False, False, True),
            ('Casual Polo Shirt',         'men',         7500,  5500,  'Premium pique polo shirt with a classic fit. Features a three-button placket and ribbed collar.',              'S,M,L,XL,XXL',         'White,Red,Green,Yellow,Black',   60, True,  True,  True),
            ('Floral Wrap Dress',         'women',       15000, 11000, 'A beautiful midi wrap dress featuring a vibrant floral print on a soft, flowy fabric.',                        'XS,S,M,L,XL',          'Floral Red,Floral Blue',         40, True,  True,  True),
            ('High-Waist Palazzo Pants',  'women',       10500, None,  'Elegant wide-leg palazzo pants in a breathable chiffon fabric.',                                               'XS,S,M,L,XL',          'Black,White,Cream,Navy',         35, False, True,  False),
            ('Ankara Peplum Top',         'traditional', 8500,  6500,  'Vibrant Ankara fabric peplum top. A celebration of Nigerian heritage.',                                        'XS,S,M,L,XL',          'Ankara Print 1,Ankara Print 2',  25, True,  True,  True),
            ('Office Pencil Skirt',       'women',       9000,  None,  'A sophisticated pencil skirt perfect for the office.',                                                         'XS,S,M,L,XL',          'Black,Navy,Charcoal,Burgundy',   45, False, False, True),
            ('Leather Oxford Brogues',    'shoes',       28000, 22000, 'Handcrafted genuine leather brogue Oxford shoes with cushioned insole.',                                       '40,41,42,43,44,45',     'Brown,Black,Tan',                20, True,  True,  True),
            ("Women's Block Heel Pumps",  'shoes',       18500, 14000, 'Elegant block heel pumps in premium faux leather.',                                                            '36,37,38,39,40,41',     'Black,Nude,Red,White',           30, True,  True,  True),
            ('Unisex Chunky Sneakers',    'shoes',       22000, 17500, 'Trendy chunky-sole sneakers with premium mesh upper.',                                                         '36,37,38,39,40,41,42,43,44', 'White,Black,Grey',            50, True,  True,  True),
            ('Slides & Sandals',          'shoes',       6500,  None,  'Comfortable foam slides perfect for casual wear.',                                                             '36,37,38,39,40,41,42,43,44', 'Black,White,Brown',           100, False, False, True),
            ('Leather Tote Bag',          'bags',        25000, 18000, 'Spacious genuine leather tote bag with multiple interior compartments.',                                       'ONE_SIZE',              'Black,Brown,Tan,Nude',           25, True,  True,  True),
            ('Mini Crossbody Bag',        'bags',        12500, None,  'Compact quilted crossbody bag with a gold chain strap.',                                                       'ONE_SIZE',              'Black,Pink,White,Gold',          40, True,  True,  False),
            ('Gold-Plated Watch',         'watches',     35000, 28000, 'Elegant gold-plated analog watch with genuine leather strap. Water resistant up to 30m.',                     'ONE_SIZE',              'Gold/Brown',                     15, True,  True,  True),
            ('Beaded Jewelry Set',        'accessories', 8500,  6000,  'Handcrafted Nigerian beaded necklace and earring set.',                                                        'ONE_SIZE',              'Multi,Red/Gold,Blue/Gold',       30, True,  True,  True),
            ('Classic Sunglasses',        'accessories', 9500,  7000,  'UV400 protective sunglasses with a classic aviator frame.',                                                    'ONE_SIZE',              'Black,Gold/Brown,Silver',        50, False, False, True),
        ]

        for name, cat_slug, price, discount, desc, sizes, colors, stock, is_new, is_featured, is_best in products_data:
            cat = categories.get(cat_slug)
            if not cat:
                continue
            product, created = Product.objects.get_or_create(
                name=name,
                defaults={
                    'category': cat, 'price': price, 'discount_price': discount,
                    'description': desc, 'sizes': sizes, 'colors': colors, 'stock': stock,
                    'is_new_arrival': is_new, 'is_featured': is_featured,
                    'is_best_seller': is_best, 'is_active': True,
                }
            )
            if created:
                self.stdout.write(f'  ✓ Product: {name}')

        # Coupons
        now = timezone.now()
        for code, dtype, dval, minord in [
            ('WELCOME10', 'percent', 10, 5000),
            ('CHIZE500',  'fixed',  500, 10000),
        ]:
            c, created = Coupon.objects.get_or_create(
                code=code,
                defaults={
                    'discount_type': dtype, 'discount_value': dval,
                    'minimum_order': minord, 'is_active': True,
                    'valid_from': now, 'valid_until': now + timedelta(days=365),
                }
            )
            if created:
                self.stdout.write(f'  ✓ Coupon: {code}')

        # ── Superadmin user + StaffProfile ─────────────────────────────
        if not User.objects.filter(username='admin').exists():
            admin_user = User.objects.create_superuser(
                'admin', 'admin@chizestores.ng', 'admin123',
                first_name='Super', last_name='Admin',
            )
            # Create matching StaffProfile so dashboard recognises the role
            try:
                from dashboard.models import StaffProfile
                sp = StaffProfile(user=admin_user, role='superadmin', is_active=True)
                sp.apply_role_defaults()
                sp.save()
                self.stdout.write('  ✓ StaffProfile created for superadmin')
            except Exception as e:
                self.stdout.write(f'  ⚠ StaffProfile skipped: {e}')
            self.stdout.write('  ✓ Superuser: admin / admin123')
        else:
            # Ensure existing admin has a StaffProfile
            admin_user = User.objects.get(username='admin')
            try:
                from dashboard.models import StaffProfile
                sp, created = StaffProfile.objects.get_or_create(
                    user=admin_user,
                    defaults={'role': 'superadmin', 'is_active': True}
                )
                if created:
                    sp.apply_role_defaults()
                    sp.save()
                    self.stdout.write('  ✓ StaffProfile linked to existing admin')
            except Exception as e:
                self.stdout.write(f'  ⚠ StaffProfile skipped: {e}')

        self.stdout.write(self.style.SUCCESS('\n✅ Demo data seeded!'))
        self.stdout.write('\n  🌐 Site:         http://127.0.0.1:8000')
        self.stdout.write('  🎛️  Dashboard:    http://127.0.0.1:8000/dashboard/')
        self.stdout.write('  🔑 Login:        admin / admin123')
        self.stdout.write('  🏷️  Coupons:      WELCOME10  |  CHIZE500\n')
