from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from .models import Novedad
from login.models import Usuario
import json
from datetime import datetime

# Create your views here.
# Create your views here.
def novedades_view(request):
    return render(request, 'novedades.html')

def save_novedad(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            # Try to get user_id from payload first, then session
            user_id = data.get('user_id') or request.session.get('user_id')
            
            if not user_id:
                return JsonResponse({'success': False, 'message': 'Usuario no autenticado.'}, status=401)

            try:
                usuario = Usuario.objects.get(id=user_id)
            except Usuario.DoesNotExist:
                return JsonResponse({'success': False, 'message': 'Usuario no encontrado.'}, status=401)

            novedad_id = data.get('id')
            
            if novedad_id:
                # Update existing
                try:
                    novedad = Novedad.objects.get(id=novedad_id, id_usuario=usuario)
                    if novedad.estado in [0, 1]: # 0: Denegado, 1: Aprobado
                        return JsonResponse({'success': False, 'message': 'No se puede editar una novedad aprobada o denegada.'})
                except Novedad.DoesNotExist:
                    return JsonResponse({'success': False, 'message': 'Novedad no encontrada.'})
            else:
                # Create new
                novedad = Novedad(id_usuario=usuario)

            novedad.titulo = data.get('titulo')
            novedad.detalle = data.get('detalle')
            novedad.fecha_inicio = data.get('fecha_inicio')
            novedad.hora_inicio = data.get('hora_inicio') or None
            
            fecha_fin = data.get('fecha_fin')
            if fecha_fin:
                novedad.fecha_fin = fecha_fin
            else:
                novedad.fecha_fin = None
                
            novedad.hora_fin = data.get('hora_fin') or None

            novedad.save()
            
            return JsonResponse({'success': True, 'message': 'Novedad guardada correctamente.'})
        except Exception as e:
            return JsonResponse({'success': False, 'message': str(e)})
    return JsonResponse({'success': False, 'message': 'Método no permitido.'})

def get_novedades(request):
    # Try to get user_id from GET params first, then session
    user_id = request.GET.get('user_id') or request.session.get('user_id')
    
    if not user_id:
        return JsonResponse({'success': False, 'message': 'Usuario no autenticado.'}, status=401)

    try:
        usuario = Usuario.objects.get(id=user_id)
        novedades = Novedad.objects.filter(id_usuario=usuario)
        events = []
        
        for n in novedades:
            # Combine date and time for calendar
            start = f"{n.fecha_inicio}"
            if n.hora_inicio:
                start += f"T{n.hora_inicio}"
            
            end = None
            if n.fecha_fin:
                end = f"{n.fecha_fin}"
                if n.hora_fin:
                    end += f"T{n.hora_fin}"
            elif n.hora_inicio:
                 # If no end date but has start time, maybe default to 1 hour or same day?
                 # For now let's keep it simple, if no end date, it's same day
                 end = start 

            # Determine category
            category = 'time'
            if not n.hora_inicio:
                category = 'allday'
            elif str(n.hora_inicio) == '00:00:00' and str(n.hora_fin) == '23:59:00':
                category = 'allday'

            # Determine status symbol
            symbol = '⏳'
            if n.estado == 1: # Aprobado
                symbol = '✔'
            elif n.estado == 0: # Denegado
                symbol = '✖'

            events.append({
                'id': str(n.id),
                'calendarId': '1',
                'title': f"{symbol} Novedad - {n.titulo}",
                'body': n.detalle,
                'start': start,
                'end': end if end else start,
                'category': category,
                'isReadOnly': True, # Disable dragging/resizing for this event
                'state': n.estado, # Custom field for frontend logic
                'raw': {
                    'titulo': n.titulo,
                    'detalle': n.detalle,
                    'fecha_inicio': n.fecha_inicio,
                    'hora_inicio': n.hora_inicio,
                    'fecha_fin': n.fecha_fin,
                    'hora_fin': n.hora_fin,
                    'estado': n.estado
                }
            })
            
        return JsonResponse({'success': True, 'events': events})
    except Usuario.DoesNotExist:
        return JsonResponse({'success': False, 'message': 'Usuario no encontrado.'}, status=401)
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})

@csrf_exempt
def delete_novedad(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            novedad_id = data.get('id')
            user_id = data.get('user_id') or request.session.get('user_id')

            if not novedad_id:
                return JsonResponse({'success': False, 'message': 'ID de novedad no proporcionado.'})

            try:
                novedad = Novedad.objects.get(id=novedad_id, id_usuario__id=user_id)
                if novedad.estado != 2: # Only Pendiente can be deleted
                     return JsonResponse({'success': False, 'message': 'Solo se pueden eliminar novedades pendientes.'})
                
                novedad.delete()
                return JsonResponse({'success': True, 'message': 'Novedad eliminada correctamente.'})
            except Novedad.DoesNotExist:
                return JsonResponse({'success': False, 'message': 'Novedad no encontrada o no autorizada.'})
        except Exception as e:
            return JsonResponse({'success': False, 'message': str(e)})
    return JsonResponse({'success': False, 'message': 'Método no permitido.'})
