# backend/views.py
from .forms import DanoneIDForm  # Import the form

# Other imports
from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from .models import Candidate, Video, CandidateVideoProgress
from .utils import append_to_google_sheet  # Import the Google Sheets append function
from datetime import datetime
import random
import string
from django.utils import timezone
import pytz

# Utility function to get the candidate from the session
def get_candidate_from_session(request):
    danone_id = request.session.get('danone_id')
    if danone_id:
        try:
            return Candidate.objects.get(danone_id=danone_id)
        except Candidate.DoesNotExist:
            return None
    return None

# Landing Page View: Input Danone ID
def landing_page(request):
    # Check if the user already has an active session
    if request.session.get('danone_id'):
        return redirect('video_list')  # Redirect to video list if session is active

    if request.method == "POST":
        form = DanoneIDForm(request.POST)
        if form.is_valid():
            danone_id = form.cleaned_data['danone_id']
            try:
                candidate = Candidate.objects.get(danone_id=danone_id)
                request.session['danone_id'] = danone_id  # Set the session for the candidate

                # Return a JSON response with the full name for the modal dialog
                return JsonResponse({'success': True, 'full_name': candidate.full_name})
            except Candidate.DoesNotExist:
                return JsonResponse({'success': False, 'error': 'Danone ID tidak sesuai'}, status=400)
        else:
            # Return a JSON response for form validation errors
            return JsonResponse({'success': False, 'error': 'Masukkan Danone ID yang sesuai'}, status=400)
    else:
        form = DanoneIDForm()

    return render(request, 'backend/landing.html', {'form': form})

def generate_unique_slug(video, candidate):
    random_suffix = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
    random_suffixes = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
    return f"{random_suffixes}{random_suffix}"

# List of Videos (with session check and end session functionality)
def video_list(request):
    candidate = get_candidate_from_session(request)  # Retrieve the candidate from session
    if not candidate:
        return redirect('landing_page')

    # Filter videos based on candidate type
    if candidate.candidate_type == 'hca':
        videos = Video.objects.filter(video_type__in=['general', 'hca'])
    else:
        videos = Video.objects.filter(video_type='general')

    progress_list = []
    total_videos = videos.count()
    watched_videos = 0

    for video in videos:
        progress, created = CandidateVideoProgress.objects.get_or_create(candidate=candidate, video=video)
        if progress.watched:
            watched_videos += 1

        # Generate unique slug for session
        slug = generate_unique_slug(video, candidate)
        request.session[f'video_slug_{video.id}'] = slug

        progress_list.append({
            'video': video,
            'progress': progress,
            'slug': slug,  # Pass slug to the context
        })

    progress_percentage = int((watched_videos / total_videos) * 100) if total_videos > 0 else 0
    remaining_videos = total_videos - watched_videos

    # Check if all videos are watched, to trigger countdown for post-test
    all_videos_watched = watched_videos == total_videos

    return render(request, 'backend/video_list.html', {
        'video_list': videos,
        'progress_list': progress_list,
        'progress_percentage': progress_percentage,
        'total_videos': total_videos,
        'watched_videos': watched_videos,
        'remaining_videos': remaining_videos,
        'candidate_name': candidate.full_name,
        'danone_id': candidate.danone_id,
        'all_videos_watched': all_videos_watched,  # Pass the flag for post-test countdown
    })

# End session and log out
def logout_view(request):
    if 'danone_id' in request.session:
        del request.session['danone_id']  # Remove the session data
    return redirect('landing_page')  # Redirect back to the landing page

def video_page(request, slug):
    candidate = get_candidate_from_session(request)
    if not candidate:
        return redirect('landing_page')

    # Loop through session slugs and match the slug
    for video in Video.objects.all():
        session_slug = request.session.get(f'video_slug_{video.id}')
        if session_slug == slug:
            progress, created = CandidateVideoProgress.objects.get_or_create(candidate=candidate, video=video)
            if request.method == 'POST':
                progress.mark_watched()
                return redirect('video_list')
            return render(request, 'backend/video.html', {'video': video, 'progress': progress})

    # If the slug doesn't match any session, redirect to the video list
    return redirect('video_list')


# Post-Test Access Button View
def post_test_button(request):
    candidate = get_candidate_from_session(request)
    if not candidate:
        return redirect('landing_page')

    # Check if the candidate has watched all videos
    total_videos = CandidateVideoProgress.objects.filter(candidate=candidate).count()
    watched_videos = CandidateVideoProgress.objects.filter(candidate=candidate, watched=True).count()

    if watched_videos < total_videos:
        return redirect('video_list')  # Redirect to video list if not all videos are watched

    user_timezone = pytz.timezone('Asia/Jakarta')
    completion_date = timezone.now().astimezone(user_timezone).strftime('%Y-%m-%d %H:%M:%S')

    # Append the candidate's information to Google Sheets
    append_to_google_sheet(candidate.full_name, candidate.danone_id, candidate.candidate_type, completion_date)

    # Redirect to the Jotform URL for post-test
    return redirect('https://form.jotform.com/251591746357466')
