"""Planning Closures Routes - GMAO Collège"""
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from ..extensions import db
from ..core.models.planning import (
    PreventiveTask, PreventiveTaskConsumable, ScheduledTask,
    Meter, MeterReading, Consumable, ConsumableUsage,
    TechnicianAvailability, AdminTask, ZoneAccessRule,
    WorkSchedule, CollegeClosure, PlanningDay, PlanningItem
)
from ..core.models.maintenance import Lot, Intervention
from ..core.models.equipment import EquipmentCategory
from ..core.models.company import Company
from datetime import datetime

from .schedules import planning_bp

@planning_bp.route('/availability')
@login_required
def availability():
    """Ancienne URL conservée pour les favoris : renvoie vers le suivi unifié."""
    return redirect(url_for('planning.time_tracking'))


@planning_bp.route('/availability/schedule/new', methods=['GET', 'POST'])
@login_required
def new_schedule():
    """Créer des horaires de travail pour plusieurs jours."""
    from app_new.core.models.planning import WorkSchedule
    
    if request.method == 'POST':
        # Récupérer les jours sélectionnés (liste de checkboxes)
        days = request.form.getlist('days')
        
        if not days:
            flash('Sélectionnez au moins un jour', 'error')
            return redirect(url_for('planning.availability'))
        
        # Créer un horaire pour chaque jour sélectionné
        for day in days:
            schedule = WorkSchedule(
                user_id=current_user.id,
                day_of_week=int(day),
                start_time=datetime.strptime(request.form.get('start_time'), '%H:%M').time() if request.form.get('start_time') else None,
                end_time=datetime.strptime(request.form.get('end_time'), '%H:%M').time() if request.form.get('end_time') else None,
                lunch_start=datetime.strptime(request.form.get('lunch_start'), '%H:%M').time() if request.form.get('lunch_start') else None,
                lunch_end=datetime.strptime(request.form.get('lunch_end'), '%H:%M').time() if request.form.get('lunch_end') else None,
                is_active=True
            )
            db.session.add(schedule)
        
        db.session.commit()
        flash(f'Horaires ajoutés pour {len(days)} jour(s)', 'success')
        return redirect(url_for('planning.availability'))
    
    days = {0: 'Dimanche', 1: 'Lundi', 2: 'Mardi', 3: 'Mercredi', 4: 'Jeudi', 5: 'Vendredi', 6: 'Samedi'}
    return render_template('planning/schedule_form.html', title='Nouvel horaire', schedule=None, days=days)


@planning_bp.route('/availability/schedule/<int:id>/delete', methods=['POST'])
@login_required
def delete_schedule(id):
    """Supprimer un horaire de travail."""
    from app_new.core.models.planning import WorkSchedule
    schedule = WorkSchedule.query.get_or_404(id)
    if schedule.user_id != current_user.id:
        flash('Non autorisé', 'danger')
        return redirect(url_for('planning.availability'))
    db.session.delete(schedule)
    db.session.commit()
    flash('Horaire supprimé', 'success')
    return redirect(url_for('planning.availability'))


@planning_bp.route('/availability/closure/new', methods=['GET', 'POST'])
@login_required
def new_closure():
    """Créer une période de vacances."""
    from app_new.core.models.planning import CollegeClosure
    
    if request.method == 'POST':
        closure = CollegeClosure(
            name=request.form.get('name'),
            start_date=datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None,
            end_date=datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None,
            closure_type=request.form.get('closure_type', 'vacances'),
            work_hours_type=request.form.get('work_hours_type', 'none'),
            notes=request.form.get('notes')
        )
        db.session.add(closure)
        db.session.commit()
        flash('Période ajoutée', 'success')
        return redirect(url_for('planning.availability'))
    
    return render_template('planning/closure_form.html', title='Nouvelle période', closure=None)


@planning_bp.route('/availability/closure/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit_closure(id):
    """Modifier une période de vacances."""
    from app_new.core.models.planning import CollegeClosure
    closure = CollegeClosure.query.get_or_404(id)
    
    days = {0: 'Dimanche', 1: 'Lundi', 2: 'Mardi', 3: 'Mercredi', 4: 'Jeudi', 5: 'Vendredi', 6: 'Samedi'}
    
    if request.method == 'POST':
        old_work_hours_type = closure.work_hours_type
        closure.name = request.form.get('name')
        closure.start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None
        closure.end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None
        closure.closure_type = request.form.get('closure_type', 'vacances')
        closure.work_hours_type = request.form.get('work_hours_type', 'none')
        closure.notes = request.form.get('notes')
        db.session.commit()
        flash('Période mise à jour', 'success')
        
        # Si on passe à "Horaires spécifiques", rester sur la page pour définir les horaires
        if old_work_hours_type != 'custom' and closure.work_hours_type == 'custom':
            return redirect(url_for('planning.edit_closure', id=closure.id))
        
        return redirect(url_for('planning.availability'))
    
    return render_template('planning/closure_form.html', title='Modifier la période', closure=closure, days=days)


@planning_bp.route('/availability/closure/<int:id>/delete', methods=['POST'])
@login_required
def delete_closure(id):
    """Supprimer une période de vacances."""
    from app_new.core.models.planning import CollegeClosure
    closure = CollegeClosure.query.get_or_404(id)
    db.session.delete(closure)
    db.session.commit()
    flash('Période supprimée', 'success')
    return redirect(url_for('planning.availability'))


@planning_bp.route('/availability/closure/<int:closure_id>/schedule/new', methods=['POST'])
@login_required
def new_closure_schedule(closure_id):
    """Ajouter des horaires pour plusieurs jours pendant une période de vacances."""
    from app_new.core.models.planning import CollegeClosure, ClosureSchedule
    
    closure = CollegeClosure.query.get_or_404(closure_id)
    
    # Récupérer les jours sélectionnés (liste de checkboxes)
    days = request.form.getlist('days')
    
    if not days:
        flash('Sélectionnez au moins un jour', 'error')
        return redirect(url_for('planning.edit_closure', id=closure_id))
    
    # Créer un horaire pour chaque jour sélectionné
    for day in days:
        schedule = ClosureSchedule(
            closure_id=closure_id,
            day_of_week=int(day),
            start_time=datetime.strptime(request.form.get('start_time'), '%H:%M').time() if request.form.get('start_time') else None,
            end_time=datetime.strptime(request.form.get('end_time'), '%H:%M').time() if request.form.get('end_time') else None,
            lunch_start=datetime.strptime(request.form.get('lunch_start'), '%H:%M').time() if request.form.get('lunch_start') else None,
            lunch_end=datetime.strptime(request.form.get('lunch_end'), '%H:%M').time() if request.form.get('lunch_end') else None,
            is_active=True
        )
        db.session.add(schedule)
    
    db.session.commit()
    flash(f'Horaires ajoutés pour {len(days)} jour(s)', 'success')
    return redirect(url_for('planning.edit_closure', id=closure_id))


@planning_bp.route('/availability/closure/<int:closure_id>/schedule/<int:schedule_id>/delete', methods=['POST'])
@login_required
def delete_closure_schedule(closure_id, schedule_id):
    """Supprimer un horaire de vacances."""
    from app_new.core.models.planning import ClosureSchedule
    
    schedule = ClosureSchedule.query.get_or_404(schedule_id)
    if schedule.closure_id != closure_id:
        flash('Horaire invalide', 'error')
        return redirect(url_for('planning.availability'))
    
    db.session.delete(schedule)
    db.session.commit()
    flash('Horaire supprimé', 'success')
    return redirect(url_for('planning.edit_closure', id=closure_id))


@planning_bp.route('/availability/leave/new', methods=['GET', 'POST'])
@login_required
def new_leave():
    """Créer un congé personnel."""
    from app_new.core.models.planning import PersonalLeave
    
    if request.method == 'POST':
        leave = PersonalLeave(
            user_id=current_user.id,
            start_date=datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None,
            end_date=datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None,
            leave_type=request.form.get('leave_type', 'conge'),
            notes=request.form.get('notes'),
            is_approved=False
        )
        db.session.add(leave)
        db.session.commit()
        flash('Congé ajouté', 'success')
        return redirect(url_for('planning.availability'))
    
    leave_types = ['conge', 'maladie', 'formation', 'autre']
    return render_template('planning/leave_form.html', title='Nouveau congé', leave=None, leave_types=leave_types)


@planning_bp.route('/availability/leave/<int:id>/delete', methods=['POST'])
@login_required
def delete_leave(id):
    """Supprimer un congé personnel."""
    from app_new.core.models.planning import PersonalLeave
    leave = PersonalLeave.query.get_or_404(id)
    if leave.user_id != current_user.id:
        flash('Non autorisé', 'danger')
        return redirect(url_for('planning.availability'))
    db.session.delete(leave)
    db.session.commit()
    flash('Congé supprimé', 'success')
    return redirect(url_for('planning.availability'))
