<script setup>
import { onMounted, ref } from 'vue';
import { api } from '@Services/Api';
import { apiTo } from './Module';

import Calendar from '@Components/Holos/Calendar.vue';

/** Propiedades */
const applicationsForCoordinator = ref([]);
const conflictDays = ref([]);
const calendarRef = ref(null);

/** Metodos */
const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('es-ES', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
};

// Función para calcular el total de días
const calculateTotalDays = (vacationPeriods) => {
    return vacationPeriods.reduce((total, period) => total + period.number_of_days, 0);
};

// Función para obtener el color del estado
const getStatusColor = (status) => {
    switch (status) {
        case 'Pendiente':
            return 'bg-yellow-100 text-yellow-800';
        case 'Aprobada':
            return 'bg-green-100 text-green-800';
        case 'Rechazada':
            return 'bg-red-100 text-red-800';
        default:
            return 'bg-gray-100 text-gray-800';
    }
};

// Método para obtener los días de conflicto del mes
const fetchConflictDays = (month) => {
    // Limpiar inmediatamente los días de conflicto para evitar el parpadeo visual
    conflictDays.value = [];
    
    api.get(apiTo('calendar-month', { month: month }), {
        onSuccess: (r) => {
            // El backend puede retornar un array vacío o un array con los días de conflicto
            conflictDays.value = r.conflict_days || [];
        },
    });
};

const approvePeriod = (periodId) => {
    api.put(apiTo('approve-period', { period: periodId }), {
        onSuccess: (r) => {
            Notify.success('Periodo aprobado correctamente');
            // recargar la página
            
        },
    });
};

const approveAll = (applicationId) => {
    api.put(apiTo('approve-request', { vacationRequest: applicationId }), {
        onSuccess: (r) => {
            Notify.success('Solicitud aprobada correctamente');
            // recargar la página
            
        },
    });
};

/** Ciclos */
onMounted(() => {
    // Cargar los días de conflicto del mes actual al montar el componente
    const initialMonth = new Date().getMonth() + 1;
    fetchConflictDays(initialMonth);

    // Cargar las solicitudes para coordinador
    api.get(apiTo('index'), {
        onSuccess: (r) => {
            applicationsForCoordinator.value = r.applications_for_coordinator;
        }
    });
});
</script>

<template>
    <div>
        <!-- Header -->
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between my-4 sm:my-8 gap-3 sm:gap-0">
            <div>
                <h1 class="text-xl sm:text-2xl font-bold text-slate-900 dark:text-slate-100">Gestión de Solicitudes</h1>
                <p class="text-sm sm:text-base text-slate-600 dark:text-slate-400">Revisa y gestiona las solicitudes de vacaciones de tu equipo</p>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-12 gap-4 lg:gap-6">
            <div class="order-2 lg:order-1 lg:col-span-8">
                <!-- Lista de solicitudes -->
                <div v-for="application in applicationsForCoordinator" :key="application.id" class="bg-white rounded-lg shadow-md p-4 sm:p-6 mb-4 sm:mb-6">
                    <!-- Información del empleado -->
                    <div class="flex flex-col sm:flex-row sm:items-center mb-4 sm:mb-6 gap-3 sm:gap-0">
                        <div class="flex items-center flex-1">
                            <div class="w-10 h-10 sm:w-12 sm:h-12 bg-gray-200 rounded-full flex items-center justify-center mr-3 sm:mr-4 overflow-hidden flex-shrink-0">
                                <img v-if="application.user.profile_photo_url" 
                                     :src="application.user.profile_photo_url" 
                                     :alt="application.user.full_name"
                                     class="w-full h-full object-cover">
                                <svg v-else class="w-5 h-5 sm:w-6 sm:h-6 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
                                        clip-rule="evenodd" />
                                </svg>
                            </div>
                            <div class="flex-1 min-w-0">
                                <div class="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 mb-1">
                                    <h2 class="text-base sm:text-lg font-semibold text-gray-900 truncate">{{ application.user.full_name }}</h2>
                                    <span :class="`px-2 py-1 text-xs rounded-full font-medium ${getStatusColor(application.status)} flex-shrink-0`">
                                        {{ application.status }}
                                    </span>
                                </div>
                                <p class="text-gray-500 text-sm">{{ application.user.department.name }}</p>
                                <p class="text-gray-400 text-xs">Días disponibles: {{ application.user.vacation_days_available }}</p>
                            </div>
                        </div>
                        <div class="text-left sm:text-right text-sm text-gray-500 flex-shrink-0">
                            <p>Solicitado: {{ formatDate(application.created_at) }}</p>
                        </div>
                    </div>

                    <!-- Conflicto -->
                    <div v-if="application.have_conflict && application.status == 'Pendiente'" class="mb-4 sm:mb-6">
                        <div class="bg-red-50 border border-red-200 rounded-lg p-3 sm:p-4">
                            <div class="flex items-start">
                                <div class="flex-shrink-0">
                                    <svg class="w-4 h-4 sm:w-5 sm:h-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                                    </svg>
                                </div>
                                <div class="ml-2 sm:ml-3 flex-1">
                                    <h3 class="text-sm font-medium text-red-800">
                                        Conflicto detectado
                                    </h3>
                                    <div class="mt-2 text-sm text-red-700">
                                        <p class="mb-3">Las siguientes fechas presentan conflictos con otras solicitudes:</p>
                                        <div class="space-y-2 sm:space-y-3">
                                            <div v-for="conflict in application.have_conflict" :key="conflict.request_id" 
                                                 class="bg-white border border-red-200 rounded-md p-2 sm:p-3">
                                                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-2 gap-1 sm:gap-0">
                                                    <span class="font-medium text-red-800">{{ conflict.user.name }}</span>
                                                </div>
                                                <div class="text-xs text-red-600 space-y-2">
                                                    <div class="flex flex-col sm:flex-row sm:justify-between gap-1 sm:gap-2">
                                                        <span class="font-medium">Período aprobado:</span>
                                                        <span class="break-all sm:break-normal">{{ formatDate(conflict.conflicting_period.start_date) }} - {{ formatDate(conflict.conflicting_period.end_date) }} ({{ conflict.conflicting_period.number_of_days }} días)</span>
                                                    </div>
                                                    <div class="flex flex-col sm:flex-row sm:justify-between gap-1 sm:gap-2">
                                                        <span class="font-medium">Período solicitado:</span>
                                                        <span class="break-all sm:break-normal">{{ formatDate(conflict.target_period.start_date) }} - {{ formatDate(conflict.target_period.end_date) }} ({{ conflict.target_period.number_of_days }} días)</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
            
                    <!-- Períodos solicitados -->
                    <div class="mb-4 sm:mb-6">
                        <h3 class="text-sm font-medium text-gray-700 mb-3">Períodos solicitados:</h3>
            
                        <div class="space-y-2">
                            <div v-for="period in application.vacation_periods" :key="period.id" 
                                 class="flex flex-col sm:flex-row sm:items-center p-3 bg-gray-50 rounded-lg gap-3 sm:gap-0">
                                <div class="flex items-center flex-1">
                                    <div class="w-6 h-6 sm:w-8 sm:h-8 bg-blue-100 rounded-full flex items-center justify-center mr-2 sm:mr-3 flex-shrink-0">
                                        <svg class="w-3 h-3 sm:w-4 sm:h-4 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd"
                                                d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z"
                                                clip-rule="evenodd" />
                                        </svg>
                                    </div>
                                    <div class="flex flex-col sm:flex-row sm:items-center sm:flex-1 gap-2">
                                        <span class="text-gray-700 text-sm">
                                            {{ formatDate(period.start_date) }} - {{ formatDate(period.end_date) }}
                                        </span>
                                        <span class="px-2 py-1 bg-blue-100 text-blue-600 text-xs rounded-full font-medium self-start sm:self-auto">
                                            {{ period.number_of_days }} {{ period.number_of_days === 1 ? 'día' : 'días' }}
                                        </span>
                                    </div>
                                </div>
                                
                                <!-- Botones de acción para períodos individuales -->
                                <div v-if="application.status === 'Pendiente'" class="flex gap-2 justify-start sm:justify-end">
                                    <button
                                        class="flex items-center justify-center gap-1 bg-green-500 hover:bg-green-600 text-white font-medium py-1.5 px-3 rounded text-xs transition-colors"
                                        @click="application.vacation_periods.length > 1 ? approvePeriod(period.id) : approveAll(application.id)"
                                    >
                                        <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd"
                                                d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                                                clip-rule="evenodd" />
                                        </svg>
                                        Aprobar
                                    </button>
                    
                                    <button
                                        class="flex items-center justify-center gap-1 bg-red-500 hover:bg-red-600 text-white font-medium py-1.5 px-3 rounded text-xs transition-colors">
                                        <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd"
                                                d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                                                clip-rule="evenodd" />
                                        </svg>
                                        Rechazar
                                    </button>
                                </div>
                            </div>
                        </div>
            
                        <!-- Total -->
                        <div class="mt-3 text-right">
                            <span class="text-sm font-medium text-gray-700">
                                Total: {{ calculateTotalDays(application.vacation_periods) }} días
                            </span>
                        </div>
                    </div>
            
                    <!-- Comentarios -->
                    <div v-if="application.comments" class="mb-4 sm:mb-6">
                        <h3 class="text-sm font-medium text-gray-700 mb-2">Comentarios:</h3>
                        <div class="p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-700 text-sm">{{ application.comments }}</span>
                        </div>
                    </div>
            
                    <!-- Motivo de rechazo -->
                    <div v-if="application.rejection_reason" class="mb-4 sm:mb-6">
                        <h3 class="text-sm font-medium text-red-700 mb-2">Motivo de rechazo:</h3>
                        <div class="p-3 bg-red-50 rounded-lg border border-red-200">
                            <span class="text-red-700 text-sm">{{ application.rejection_reason }}</span>
                        </div>
                    </div>
            
                    <!-- Botones de acción -->
                    <div v-if="application.status === 'Pendiente' && application.vacation_periods.length > 1" class="flex flex-col sm:flex-row gap-2 sm:gap-3">
                        <button
                            class="flex items-center justify-center gap-2 bg-green-500 hover:bg-green-600 text-white font-medium py-2.5 sm:py-2 px-4 rounded-lg transition-colors"
                            @click="approveAll(application.id)"
                        >
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd"
                                    d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                                    clip-rule="evenodd" />
                            </svg>
                            Aprobar todo
                        </button>
            
                        <button
                            class="flex items-center justify-center gap-2 bg-red-500 hover:bg-red-600 text-white font-medium py-2.5 sm:py-2 px-4 rounded-lg transition-colors">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd"
                                    d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                                    clip-rule="evenodd" />
                            </svg>
                            Rechazar todo
                        </button>
                    </div>
                </div>
            
                <!-- Mensaje cuando no hay solicitudes -->
                <div v-if="!applicationsForCoordinator || applicationsForCoordinator.length === 0" 
                     class="text-center py-8 sm:py-12 px-4">
                    <div class="w-12 h-12 sm:w-16 sm:h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <svg class="w-6 h-6 sm:w-8 sm:h-8 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                        </svg>
                    </div>
                    <h3 class="text-base sm:text-lg font-medium text-gray-900 mb-2">No hay solicitudes pendientes</h3>
                    <p class="text-sm sm:text-base text-gray-500">Tu equipo no tiene solicitudes de vacaciones que requieran revisión.</p>
                </div>
            </div>
            <div class="order-1 lg:order-2 lg:col-span-4">
                <Calendar 
                    ref="calendarRef"
                    :conflictDays="conflictDays"
                    @monthChanged="fetchConflictDays"
                />
            </div>
        </div>
    </div>
</template>
