from decimal import Decimal

from django.db.models import Avg
from django.shortcuts import redirect, render

from products.models import Product


def _format_discount_offer(product):
    if not product or product.price == 0 or product.discount_price is None:
        return None
    savings = product.price - product.discount_price
    percent = int((savings / product.price * Decimal('100')).quantize(Decimal('1')))
    return {
        'title': f'{percent}% off',
        'description': f'{product.name} now available for Rs. {product.discount_price:.0f}',
        'note': f'Save Rs. {savings:.0f} on {product.category}',
    }


def home(request):
    trending_products = Product.objects.filter(featured=True).order_by('-created_at')[:4]
    if not trending_products.exists():
        trending_products = Product.objects.order_by('-created_at')[:4]

    aggregates = Product.objects.aggregate(avg_rating=Avg('rating'))
    discounted_products = list(Product.objects.filter(discount_price__isnull=False).order_by('discount_price')[:6])
    best_discount = None
    if discounted_products:
        best_discount = max(
            discounted_products,
            key=lambda p: ((p.price - p.discount_price) / p.price) if p.price else Decimal('0'),
        )

    featured_count = Product.objects.filter(featured=True).count()
    categories_count = Product.objects.values('category').exclude(category='').distinct().count()

    special_deals = []
    offer_deal = _format_discount_offer(best_discount)
    if offer_deal:
        special_deals.append(offer_deal)

    special_deals.append({
        'title': f'{len(discounted_products)} offers live',
        'description': 'Discounts available across top Nepali categories.',
        'note': 'Browse products with extra savings today.',
    })

    if featured_count:
        special_deals.append({
            'title': 'Featured Seller Picks',
            'description': f'{featured_count} curated products from trusted sellers.',
            'note': 'Popular with Nepali shoppers.',
        })
    else:
        special_deals.append({
            'title': 'Daily Deals',
            'description': 'Fresh discount offers updated every day.',
            'note': 'Check back for more savings.',
        })

    advertised_products = sorted(
        discounted_products,
        key=lambda p: ((p.price - p.discount_price) / p.price if p.price else Decimal('0')),
        reverse=True,
    )[:4]

    if not advertised_products:
        advertised_products = list(trending_products[:4])

    for index, product in enumerate(advertised_products):
        savings = (product.price - product.discount_price) if product.discount_price else Decimal('0')
        percent = int((savings / product.price * Decimal('100')).quantize(Decimal('1'))) if product.price else 0
        if percent >= 50:
            label = 'Mega Deal'
        elif percent >= 30:
            label = 'Hot Deal'
        elif percent >= 15:
            label = 'Limited Time'
        else:
            label = 'Special Offer'
        if product.featured and percent >= 10:
            label = 'Featured Deal'
        product.deal_label = label

    return render(
        request,
        'core/home.html',
        {
            'trending_products': trending_products,
            'total_products': Product.objects.count(),
            'featured_products': featured_count,
            'categories_count': categories_count,
            'avg_rating': aggregates.get('avg_rating') or 0,
            'special_deals': special_deals,
            'advertised_products': advertised_products,
        },
    )


def about(request):
    return render(request, 'core/about.html')


def support(request):
    return render(request, 'core/support.html')


def set_language_preference(request):
    if request.method == 'POST':
        language = request.POST.get('language', 'en').strip().lower()
        next_url = request.POST.get('next', '/').strip()
    else:
        language = request.GET.get('language', 'en').strip().lower()
        next_url = request.GET.get('next', '/').strip()

    if language not in {'en', 'ne'}:
        language = 'en'

    request.session['site_language'] = language
    if next_url.startswith('/'):
        return redirect(next_url)
    return redirect('home')


def landing(request):
    return render(request, 'core/landing.html')


def settings_view(request):
    if request.method == 'POST':
        delivery_location = request.POST.get('delivery_location', '').strip()
        if delivery_location:
            request.session['delivery_location'] = delivery_location
        else:
            request.session.pop('delivery_location', None)
        return redirect('settings')

    return render(request, 'core/settings.html')
