from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from .models import Appointment, Unavailability
from datetime import date, timedelta
from django.http import JsonResponse,HttpResponseForbidden,HttpResponse
from users.models import User
from .forms import UnavailabilityForm
from django.utils import timezone


@login_required
def doctor_list(request):
    doctors = User.objects.filter(is_doctor=True)
    return render(request, 'doctor_list.html', {'doctors': doctors})

@login_required
def doctor_availability(request, doctor_id):
    doctor = get_object_or_404(User, pk=doctor_id, is_doctor=True)
    today = date.today()
    next_month = today + timedelta(days=30)
    all_dates = [today + timedelta(days=i) for i in range((next_month - today).days)]
    unavailable_dates = Unavailability.objects.filter(doctor=doctor).values_list('date', flat=True)
    available_dates = [d for d in all_dates if d not in unavailable_dates]
    
    context = {
        'doctor': doctor,
        'available_dates': available_dates,
        'unavailable_dates': unavailable_dates,
    }
    return render(request, 'doctor_availability.html', context)

@login_required
def doctor_availability_json(request, doctor_id):
    doctor = get_object_or_404(User, pk=doctor_id, is_doctor=True)
    today = date.today()
    next_month = today + timedelta(days=30)
    all_dates = [today + timedelta(days=i) for i in range((next_month - today).days)]
    unavailable_dates = Unavailability.objects.filter(doctor=doctor).values_list('date', flat=True)
    
    events = []

    # Ajouter les jours d'indisponibilité
    for unavailability_date in unavailable_dates:
        events.append({
            'title': 'Indisponible',
            'start': unavailability_date.strftime('%Y-%m-%d'),
            'backgroundColor': 'grey',  # Couleur pour les jours d'indisponibilité
            'borderColor': 'grey',
        #    'editable': false,
            'rendering': 'background'  # Utilisé pour afficher les jours d'indisponibilité en arrière-plan
        })

    # Ajouter les jours disponibles
    for d in all_dates:
        if d not in unavailable_dates:
            events.append({
                'title': 'Disponible',
                'start': d.strftime('%Y-%m-%d'),
                'backgroundColor': 'green',  # Couleur pour les jours disponibles
                'borderColor': 'green',
            })

    return JsonResponse(events, safe=False)

@login_required
def book_appointment(request, doctor_id):
    doctor = get_object_or_404(User, pk=doctor_id, is_doctor=True)
    if request.method == 'POST':
        patient = request.user
        date = request.POST['date']
        time = request.POST['time']
        motif = request.POST['motif']
        appointment = Appointment.objects.create(patient=patient, doctor=doctor, date=date, time=time, motif=motif)
        return redirect('doctor_list')
    return render(request, 'book_appointment.html', {'doctor': doctor})

#Afficher les rendez-vous du docteur dans le calendrier fullCalendar 
@login_required
def doctor_appointment_list(request, doctor_id):
    doctor = get_object_or_404(User, pk=doctor_id, is_doctor=True)
    appointments = Appointment.objects.filter(doctor=doctor)
    return render(request, 'appointment_list.html', {'doctor': doctor, 'appointments': appointments})

@login_required
def doctor_appointments_json(request, doctor_id):
    doctor = get_object_or_404(User, pk=doctor_id, is_doctor=True)
    appointments = Appointment.objects.filter(doctor=doctor)
    unavailabilities = Unavailability.objects.filter(doctor=doctor).values('id', 'date', 'motif')
    
    events = []
    for appointment in appointments:
        color = 'blue'  # Couleur par défaut pour les rendez-vous en attente
        if appointment.status == 'accepted':
            color = 'green'
        elif appointment.status == 'rejected':
            color = 'red'

        # Vérifier si le rendez-vous est passé
        is_past = appointment.date < timezone.now().date()
        
        events.append({
            'id': appointment.id,  # Ajouter l'ID pour l'identifier dans le frontend
            'title': f'RDV avec {appointment.patient.get_full_name()}',
            'start': appointment.date,
            'description': appointment.motif,
            'status': appointment.status,
            'backgroundColor': color,  # Couleur en fonction du statut
            'borderColor': color,
            'isPast': is_past,  # Indicateur pour savoir si c'est un rendez-vous passé
        })
        
    # Ajouter les jours d'indisponibilité
    for unavailability in unavailabilities:
        date_unavailability = unavailability['date']

        # Vérifier si la date est passée
        if date_unavailability >= timezone.now().date():

            events.append({
                'id': unavailability['id'],
                'title': 'Indisponible',
                'start': unavailability['date'].strftime('%Y-%m-%d'),
                'backgroundColor': 'grey',  # Couleur pour les jours d'indisponibilité
                'borderColor': 'grey',
                'rendering': 'background',  # Utilisé pour afficher les jours d'indisponibilité en arrière-plan
                'description': unavailability['motif'],
                'isUnavailability': True,  # Ceci est une indisponibilité
                'isPast': False,  # La date n'est pas passée
            })  

    return JsonResponse(events, safe=False)



#Afficher les rendez-vous du patient dans le celendrier fullcalendar
@login_required
def patient_appointments_list(request, patient_id):
    patient = get_object_or_404(User, pk=patient_id, is_patient=True)
    appointments = Appointment.objects.filter(patient=patient)
    return render(request, 'patient_appoint.html', {'patient': patient, 'appointments': appointments})

@login_required
def patient_appointments_json(request, patient_id):
    patient = get_object_or_404(User, pk=patient_id, is_patient=True)
    appointments = Appointment.objects.filter(patient=patient)
    
    events = []
    for appointment in appointments:

        color = 'blue'  # Couleur par défaut pour les rendez-vous en attente
        if appointment.status == 'accepted':
            color = 'green'
        elif appointment.status == 'reporter':
            color = 'yellow'
        elif appointment.status == 'rejected':
            color = 'red'

        events.append({
            'id': appointment.id,  # Ajouter l'ID pour l'identifier dans le frontend
            'title': f'Rendez-vous avec {appointment.doctor.get_full_name()}',
            'start': f'{appointment.date}T{appointment.time}',
            'description': appointment.motif,
            'status': appointment.status,
        })
    
    return JsonResponse(events, safe=False)


#ajout de l'indisponibilité du medecin
@login_required
def add_unavailability(request):
    if request.method == 'POST':
        form = UnavailabilityForm(request.POST)
        if form.is_valid():
            unavailability = form.save(commit=False)
            unavailability.doctor = request.user
            unavailability.save()
            return redirect('medecin_dashboard',)
    else:
        form = UnavailabilityForm()
    return render(request, 'appointment_list.html', {'form': form})


@login_required
@require_POST
@csrf_exempt
def update_appointment_status(request, appointment_id):
    appointment = get_object_or_404(Appointment, pk=appointment_id)
    new_status = request.POST.get('status')

    if new_status in ['accepted', 'rejected', 'pending']:
        appointment.status = new_status
        appointment.save()
        return JsonResponse({'success': True, 'status': appointment.status})
    
    return JsonResponse({'success': False, 'error': 'Invalid status'}, status=400)

@login_required
@require_POST
@csrf_exempt
def delete_unavailability(request, unavailability_id):
    unavailability = get_object_or_404(Unavailability, pk=unavailability_id)
    unavailability.delete()
    return JsonResponse({'success': True})

@require_POST
def accept_appointment(request, appointment_id):
    if request.method == 'POST':
        appointment = get_object_or_404(Appointment, id=appointment_id)
        appointment.status = 'accepted'
        appointment.save()
        return JsonResponse({'status': 'accepted'}, status=200)  # Réponse JSON pour succès

@require_POST
def reject_appointment(request, appointment_id):
    if request.method == 'POST':
        appointment = get_object_or_404(Appointment, id=appointment_id)
        appointment.status = 'rejected'
        appointment.save()
        return JsonResponse({'status': 'rejected'}, status=200)  # Réponse JSON pour succès
    
    