from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, authenticate, logout, update_session_auth_hash
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse, HttpResponseForbidden
from django.conf import settings
from django.utils import timezone
from django.core.paginator import Paginator
from django.views.decorators.http import require_POST
from django.db.models import Q
import json

from .forms import (
    SignUpForm, LoginForm, ForgotPasswordForm, ResetPasswordForm,
    ProfileUpdateForm, SecuritySettingsForm
)
from .models import Profile, Subscription, DashboardCard


# -------------------------
# SIGN UP VIEW
# -------------------------
def signup_view(request):
    if request.user.is_authenticated:
        return redirect('home')
    
        
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            try:
                user = form.save()
                return JsonResponse({
                    'success': True,
                    'message': "Account created successfully! You can now log in.",
                    'redirect': '/login/'
                })
            except Exception as e:
                import logging
                logging.error(f"Signup Error: {str(e)}")
                return JsonResponse({
                    'success': False,
                    'message': f"An error occurred: {str(e)}",
                    'errors': {'general': 'Please try again later.'}
                })
        else:
            # Return form errors as JSON
            errors = {}
            for field, field_errors in form.errors.items():
                errors[field] = field_errors[0] if field_errors else ''
            
            return JsonResponse({
                'success': False,
                'message': 'Please correct the highlighted errors.',
                'errors': errors
            })
    else:
        form = SignUpForm()
    
    return render(request, 'index.html', {'form': form})


# -------------------------
# LOGIN VIEW
# -------------------------
def login_view(request):
    if request.user.is_authenticated:
        return redirect('home')

    if request.method == "POST":
        try:
            data = json.loads(request.body)
            email = data.get("email")
            password = data.get("password")
            remember = data.get("remember", False)

            # Attempt authentication
            authenticated_user = authenticate(request, username=email, password=password)
            if authenticated_user is not None:
                # Perform login
                login(request, authenticated_user)
                
                # Handle remember me
                if remember:
                    age = getattr(settings, 'SESSION_COOKIE_AGE', 1209600)
                    request.session.set_expiry(age)
                else:
                    request.session.set_expiry(0)
                
                return JsonResponse({
                    "success": True,
                    "redirect": "/"
                })
            else:
                return JsonResponse({
                    "success": False,
                    "errors": {"email": "Invalid email or password."}
                })
                
        except Exception as e:
            print("Login Error:", e)
            return JsonResponse({
                "success": False,
                "errors": {"general": "Something went wrong. Please try again."}
            })
    else:
        return render(request, "signin.html")


# -------------------------
# DASHBOARD VIEW
# -------------------------
def dashboard_view(request):
    user = request.user if request.user.is_authenticated else None
    
    # Check if user has active subscription
    has_active_subscription = False
    if user and user.is_authenticated:
        has_active_subscription = Subscription.objects.filter(
            user=user,
            status='active'
        ).exists()

    # Fetch active dashboard cards from database
    dashboard_cards = DashboardCard.objects.filter(is_active=True)
    dashboard_items = []
    for card in dashboard_cards:
        item = {
            "title": card.title,
            "image": card.get_image_url(),
            "link": card.link if card.link else None,
            "has_video": False
        }
        
        # Check if card has video and add video URL
        if hasattr(card, 'video') and card.video:
            item["video"] = card.video.url
            item["has_video"] = True
        elif hasattr(card, 'video_url') and card.video_url:
            item["video_url"] = card.video_url
            item["has_video"] = True
            
        dashboard_items.append(item)
    
    return render(request, 'dashboard.html', {
        'user': user, 
        'dashboard_items': dashboard_items,
        'has_active_subscription': has_active_subscription
    })


# -------------------------
# SETTINGS VIEW
# -------------------------
def settings_view(request):
    user = request.user if request.user.is_authenticated else None

    if request.method == 'POST':
        # Only update if user is logged in
        if not request.user.is_authenticated:
            messages.error(request, "Please log in to update your profile.")
            return redirect('login')

        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        current_password = request.POST.get('current_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        # Update basic info
        if first_name:
            user.first_name = first_name
        if last_name:
            user.last_name = last_name
        if email:
            user.email = email
            user.username = email

        # Password change logic
        if new_password:
            if not user.check_password(current_password):
                messages.error(request, "Current password is incorrect.")
                return redirect('settings')
            if new_password != confirm_password:
                messages.error(request, "New passwords do not match.")
                return redirect('settings')
            user.set_password(new_password)
            update_session_auth_hash(request, user)
            messages.success(request, "Password updated successfully!")

        user.save()
        messages.success(request, "Profile updated successfully!")
        return redirect('settings')

    return render(request, 'setting.html', {'user': user})


# -------------------------
# LOGOUT VIEW
# -------------------------
def logout_view(request):
    logout(request)
    messages.info(request, "You have been logged out successfully.")
    return redirect('login')


# -------------------------
# PASSWORD RESET PAGE
# -------------------------
def reset_view(request):
    return render(request, 'reset.html')


# -------------------------
# TERMS PAGE
# -------------------------
def term_view(request):
    return render(request, 'term.html')


# -------------------------
# VERIFICATION PAGE
# -------------------------
def verification_view(request):
    return render(request, 'verificationcode.html')


# -------------------------
# INDEX / DEFAULT PAGE
# -------------------------
def index(request):
    user = request.user if request.user.is_authenticated else None
    
    # Check if user has active subscription
    has_active_subscription = False
    if user and user.is_authenticated:
        has_active_subscription = Subscription.objects.filter(
            user=user,
            status='active'
        ).exists()

    # Fetch active dashboard cards from database
    dashboard_cards = DashboardCard.objects.filter(is_active=True)
    dashboard_items = []
    for card in dashboard_cards:
        item = {
            "title": card.title,
            "image": card.get_image_url(),
            "link": card.link if card.link else None,
            "has_video": False
        }
        
        # Check if card has video and add video URL
        if hasattr(card, 'video') and card.video:
            item["video"] = card.video.url
            item["has_video"] = True
        elif hasattr(card, 'video_url') and card.video_url:
            item["video_url"] = card.video_url
            item["has_video"] = True
            
        dashboard_items.append(item)
    
    return render(request, 'dashboard.html', {
        'user': user, 
        'dashboard_items': dashboard_items,
        'has_active_subscription': has_active_subscription
    })
