from orders.models import Order
from products.models import Product

CATEGORY_ICONS = {
    'fashion': '👕',
    'mobile': '📱',
    'mobiles': '📱',
    'electronics': '💻',
    'home': '🛋️',
    'appliances': '📺',
    'toys': '🧸',
    'beauty': '💄',
    'books': '📚',
    'sports': '🏀',
    'groceries': '🛒',
    'health': '💊',
    'jewelry': '💍',
    'home decor': '🕯️',
    'stationery': '📝',
    'pets': '🐾',
    'accessories': '🧢',
    'shoes': '👟',
    'kids': '🧒',
    'tools': '🛠️',
    'office': '📎',
    'kitchen': '🍳',
    'travel': '✈️',
    'automotive': '🚗',
    'garden': '🌿',
    'party': '🎉',
}

DEFAULT_CATEGORIES = [
    {'value': 'fashion', 'name': 'Fashion', 'icon': '👕'},
    {'value': 'mobiles', 'name': 'Mobiles', 'icon': '📱'},
    {'value': 'electronics', 'name': 'Electronics', 'icon': '💻'},
    {'value': 'home', 'name': 'Home', 'icon': '🛋️'},
    {'value': 'appliances', 'name': 'Appliances', 'icon': '📺'},
    {'value': 'toys', 'name': 'Toys', 'icon': '🧸'},
    {'value': 'beauty', 'name': 'Beauty', 'icon': '💄'},
    {'value': 'books', 'name': 'Books', 'icon': '📚'},
    {'value': 'sports', 'name': 'Sports', 'icon': '🏀'},
    {'value': 'groceries', 'name': 'Groceries', 'icon': '🛒'},
    {'value': 'health', 'name': 'Health', 'icon': '💊'},
    {'value': 'jewelry', 'name': 'Jewelry', 'icon': '💍'},
    {'value': 'pets', 'name': 'Pets', 'icon': '🐾'},
    {'value': 'shoes', 'name': 'Shoes', 'icon': '👟'},
]

EN_LABELS = {
    'home': 'Home',
    'products': 'Products',
    'all_products': 'All Products',
    'featured': 'Featured',
    'categories': 'Categories',
    'cart': 'Cart',
    'wishlist': 'Wishlist',
    'about': 'About',
    'support': 'Help & Support',
    'orders': 'Orders',
    'my_profile': 'My Profile',
    'my_orders': 'My Orders',
    'login': 'Login',
    'register': 'Register',
    'logout': 'Logout',
    'shop_now': 'Shop Now',
    'learn_more': 'Learn More',
    'choose_language': 'Language',
    'english': 'English',
    'nepali': 'Nepali',
    'theme_toggle': 'Light Mode',
    'for_you': 'For You',
}

NE_LABELS = {
    'home': 'Griha',
    'products': 'Utpadan',
    'all_products': 'Sabai Utpadan',
    'featured': 'Bisesh',
    'categories': 'Shreni',
    'cart': 'Kart',
    'wishlist': 'Icchha Suchi',
    'about': 'Hamro Barema',
    'support': 'Sahayog',
    'orders': 'Orderharu',
    'my_profile': 'Mero Profile',
    'my_orders': 'Mero Order',
    'login': 'Login',
    'register': 'Darta',
    'logout': 'Logout',
    'shop_now': 'Ahile Kinmel',
    'learn_more': 'Thap Jankari',
    'choose_language': 'Bhasha',
    'for_you': 'Tapaiko Lagi',
    'english': 'English',
    'nepali': 'Nepali',
    'theme_toggle': 'Light Mode',
}


def cart_summary(request):
    cart = request.session.get('cart', {})
    total_items = sum(cart.values()) if isinstance(cart, dict) else 0
    order_count = 0

    if request.user.is_authenticated:
        order_count = Order.objects.filter(user=request.user).count()

    return {
        'cart_count': total_items,
        'order_count': order_count,
    }


def language_context(request):
    site_language = request.session.get('site_language', 'en')
    if site_language not in {'en', 'ne'}:
        site_language = 'en'

    ui = NE_LABELS if site_language == 'ne' else EN_LABELS

    raw_categories = Product.objects.values_list('category', flat=True).exclude(category='').distinct()
    category_items = []
    seen = set()
    for raw_value in raw_categories:
        cleaned = (raw_value or '').strip()
        if not cleaned:
            continue
        key = cleaned.lower()
        if key in seen:
            continue
        seen.add(key)
        category_items.append({
            'value': cleaned,
            'name': cleaned.title(),
            'icon': CATEGORY_ICONS.get(key, '🛍️'),
        })

    for default_category in DEFAULT_CATEGORIES:
        if default_category['value'].lower() not in seen:
            category_items.append(default_category)
            seen.add(default_category['value'].lower())

    delivery_location = request.session.get('delivery_location', '').strip()
    if not delivery_location and request.user.is_authenticated:
        last_address = Order.objects.filter(user=request.user).exclude(address='').order_by('-created_at').values_list('address', flat=True).first()
        if last_address:
            delivery_location = last_address.split('\n', 1)[0].strip()

    return {
        'site_language': site_language,
        'ui': ui,
        'language_options': [
            {'code': 'en', 'label': ui['english']},
            {'code': 'ne', 'label': ui['nepali']},
        ],
        'categories': category_items,
        'delivery_location': delivery_location,
    }
