from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.db.models import Count
from django.db.models.functions import TruncDay
from django.utils import timezone
from datetime import timedelta
import json


@login_required
def dashboard_view(request):
    from booking.models import Appointment
    from scheduler.models import AppointmentType

    appointments = Appointment.objects.filter(
        user=request.user,
        appointment_type__deleted_at__isnull=True
    ).select_related(
        'appointment_type',
        'resource'
    ).order_by('date', 'start_time')[:5]

    appointment_types = AppointmentType.objects.filter(user=request.user, deleted_at__isnull=True)

    from scheduler.models import Business
    business = Business.objects.filter(user=request.user).first()

    today = timezone.localdate()
    week_start = today - timedelta(days=today.weekday())
    week_end = week_start + timedelta(days=6)

    today_count = Appointment.objects.filter(user=request.user, date=today, status__in=['confirmed', 'pending']).count()
    week_count = Appointment.objects.filter(user=request.user, date__gte=week_start, date__lte=week_end, status__in=['confirmed', 'pending']).count()

    context = {
        'appointments': appointments,
        'appointment_types': appointment_types,
        'business': business,
        'today_count': today_count,
        'week_count': week_count,
    }
    return render(request, 'core/dashboard.html', context)

@login_required
def dashboard_activity_api(request):
    from booking.models import Appointment
    
    # Datos del mes actual
    today = timezone.localdate()
    start_of_month = today.replace(day=1)
    if today.month == 12:
        end_of_month = today.replace(day=31)
    else:
        end_of_month = (today.replace(month=today.month + 1, day=1) - timedelta(days=1))
    
    days_in_month = end_of_month.day
    
    # Agrupar citas por día Y estado
    qs = (
        Appointment.objects.filter(user=request.user, date__range=[start_of_month, end_of_month])
        .annotate(day=TruncDay('date'))
        .values('day', 'status')
        .annotate(count=Count('id'))
        .order_by('day')
    )
    
    labels = [str(i) for i in range(1, days_in_month + 1)]
    
    # Inicializar datasets para cada estado
    datasets = {
        'confirmed': [0] * days_in_month,
        'pending': [0] * days_in_month,
        'cancelled': [0] * days_in_month,
        'no_show': [0] * days_in_month
    }
    
    for entry in qs:
        day_index = entry['day'].day - 1
        status = entry['status']
        if status in datasets and 0 <= day_index < days_in_month:
            datasets[status][day_index] = entry['count']
            
    return JsonResponse({
        'labels': labels,
        'datasets': datasets
    })
