
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
from .models import Shop, Theme
from .forms import ShopForm, ThemeForm, MpesaSettingsForm, SMTPSettingsForm, SMSSettingsForm

@login_required
def settings_view(request):
    """Main settings view with form handling"""
    try:
        shop = Shop.objects.first()
    except Exception as e:
        # Log the error and create a default shop
        print(f"Error fetching shop: {e}")
        shop = None
    
    try:
        theme = Theme.objects.first()
    except Exception as e:
        # Log the error and create a default theme
        print(f"Error fetching theme: {e}")
        theme = None
    
    if not shop:
        try:
            shop = Shop.objects.create(
                name="Sales Shark",
                address="Nairobi, Kenya",
                phone="+254700000000",
                email="info@salesshark.com"
            )
        except Exception as e:
            print(f"Error creating shop: {e}")
            # Create a basic shop object for template rendering
            shop = Shop(
                name="Sales Shark",
                address="Nairobi, Kenya",
                phone="+254700000000",
                email="info@salesshark.com"
            )
    
    if not theme:
        try:
            theme = Theme.objects.create(mode='light', primary_color='#28a745')
        except Exception as e:
            print(f"Error creating theme: {e}")
            # Create a basic theme object for template rendering
            theme = Theme(mode='light', primary_color='#28a745')
    
    if request.method == 'POST':
        form_type = request.POST.get('form_type')
        
        if form_type == 'shop_details':
            form = ShopForm(request.POST, request.FILES, instance=shop)
            if form.is_valid():
                form.save()
                messages.success(request, 'Shop details updated successfully!')
            else:
                messages.error(request, 'Please correct the errors in the shop details form.')
        
        elif form_type == 'mpesa_settings':
            form = MpesaSettingsForm(request.POST, instance=shop)
            if form.is_valid():
                form.save()
                messages.success(request, 'Mpesa API settings updated successfully!')
            else:
                messages.error(request, 'Please correct the errors in the Mpesa settings form.')
        
        elif form_type == 'smtp_settings':
            form = SMTPSettingsForm(request.POST, instance=shop)
            if form.is_valid():
                form.save()
                messages.success(request, 'SMTP email settings updated successfully!')
            else:
                messages.error(request, 'Please correct the errors in the SMTP settings form.')
        
        elif form_type == 'sms_settings':
            form = SMSSettingsForm(request.POST, instance=shop)
            if form.is_valid():
                form.save()
                messages.success(request, 'SMS API settings updated successfully!')
            else:
                messages.error(request, 'Please correct the errors in the SMS settings form.')
        
        elif form_type == 'theme':
            form = ThemeForm(request.POST, instance=theme)
            if form.is_valid():
                form.save()
                messages.success(request, 'Theme settings updated successfully!')
            else:
                messages.error(request, 'Please correct the errors in the theme settings form.')
        
        return redirect('shop_backend:settings')
    
    # Initialize forms for display
    shop_details_form = ShopForm(instance=shop)
    mpesa_settings_form = MpesaSettingsForm(instance=shop)
    smtp_settings_form = SMTPSettingsForm(instance=shop)
    sms_settings_form = SMSSettingsForm(instance=shop)
    theme_form = ThemeForm(instance=theme)
    
    return render(request, 'settings/shop_settings.html', {
        'shop': shop,
        'theme': theme,
        'shop_details_form': shop_details_form,
        'mpesa_settings_form': mpesa_settings_form,
        'smtp_settings_form': smtp_settings_form,
        'sms_settings_form': sms_settings_form,
        'theme_form': theme_form,
    })

@login_required
def shop_details(request):
    """View shop details"""
    try:
        shop = Shop.objects.first()
    except Exception as e:
        print(f"Error fetching shop: {e}")
        shop = None
    
    if not shop:
        try:
            shop = Shop.objects.create(
                name="Sales Shark",
                address="Nairobi, Kenya",
                phone="+254700000000",
                email="info@salesshark.com"
            )
        except Exception as e:
            print(f"Error creating shop: {e}")
            shop = Shop(
                name="Sales Shark",
                address="Nairobi, Kenya",
                phone="+254700000000",
                email="info@salesshark.com"
            )
    
    return render(request, 'settings/shop_details.html', {
        'shop': shop,
    })

@login_required
def edit_shop_details(request):
    """Edit shop details"""
    shop = Shop.objects.first()
    
    if not shop:
        shop = Shop.objects.create(
            name="Sales Shark",
            address="Nairobi, Kenya",
            phone="+254700000000",
            email="info@salesshark.com"
        )
    
    if request.method == 'POST':
        form = ShopForm(request.POST, request.FILES, instance=shop)
        if form.is_valid():
            form.save()
            messages.success(request, 'Shop details updated successfully!')
            return redirect('shop_details')
    else:
        form = ShopForm(instance=shop)
    
    return render(request, 'settings/edit_shop_details.html', {
        'form': form,
        'shop': shop,
    })

@login_required
def theme_settings(request):
    """Theme settings view"""
    try:
        theme = Theme.objects.first()
    except Exception as e:
        print(f"Error fetching theme: {e}")
        theme = None
    
    if not theme:
        try:
            theme = Theme.objects.create(mode='light', primary_color='#28a745')
        except Exception as e:
            print(f"Error creating theme: {e}")
            theme = Theme(mode='light', primary_color='#28a745')
    
    if request.method == 'POST':
        form = ThemeForm(request.POST, instance=theme)
        if form.is_valid():
            form.save()
            messages.success(request, 'Theme settings updated successfully!')
            return redirect('shop_backend:theme_settings')
    else:
        form = ThemeForm(instance=theme)
    
    return render(request, 'settings/theme_settings.html', {
        'form': form,
        'theme': theme,
    })

@require_POST
@csrf_exempt
def toggle_theme(request):
    """Toggle theme via AJAX"""
    try:
        data = json.loads(request.body)
        theme_mode = data.get('theme', 'light')
        
        # Validate theme mode
        if theme_mode not in ['light', 'dark']:
            return JsonResponse({'error': 'Invalid theme mode'}, status=400)
        
        # Get or create theme
        theme = Theme.objects.first()
        if not theme:
            theme = Theme.objects.create(mode=theme_mode, primary_color='#28a745')
        else:
            theme.mode = theme_mode
            theme.save()
        
        return JsonResponse({'success': True, 'theme': theme_mode})
    
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
