<script setup>
import { onMounted, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { api, useForm } from '@Services/Api';
import { apiTo, viewTo } from './Module'

import GoogleIcon from '@Shared/GoogleIcon.vue';
import Form from './Form.vue';

/** Definidores */
const router = useRouter();

const form = useForm({
    periods: [
        {
            start_date: '',
            end_date: '',
            number_of_days: 0,
        }
    ],
    comments: ''
});

const availableDays = ref(0);
const formRef = ref(null);

// Calcular días restantes
const remainingDays = computed(() => {
    if (!formRef.value) return availableDays.value;
    return availableDays.value - formRef.value.totalSelectedDays;
});

// Calcular total de días seleccionados
const totalSelectedDays = computed(() => {
    if (!formRef.value) return 0;
    return formRef.value.totalSelectedDays;
});

// Obtener períodos con datos
const periodsWithData = computed(() => {
    return form.periods.filter(period => period.start_date && period.end_date && period.number_of_days > 0);
});

/** Métodos */
function submit() {
    form.post(apiTo('store'), {
        onSuccess: (res) => {
            Notify.success(Lang('created'));
            router.push(viewTo({ name: 'index' }));
        }
    });
}

/** Ciclos */
onMounted(() => {
    api.get(route('resources.available-days'), {
        onSuccess: (res) => {
            availableDays.value = res.available_days;
        }
    });
});
</script>

<template>
    <div>
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center gap-4 mb-4">
            <RouterLink :to="viewTo({ name: 'index' })">
                    <button class="flex items-center justify-center w-10 h-10 rounded-lg bg-slate-100 hover:bg-slate-200 with-transition dark:bg-slate-800 dark:hover:bg-slate-700">
                        <GoogleIcon name="arrow_back" class="text-slate-600 dark:text-slate-300" />
                    </button>
            </RouterLink>
                <div>
                    <h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">Solicitar Vacaciones</h1>
                    <p class="text-slate-600 dark:text-slate-400">Completa el formulario para solicitar tus días de vacaciones.</p>
                </div>
            </div>
        </div>

        <!-- Layout de dos columnas -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Formulario - Columna izquierda (2/3) -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 dark:bg-slate-800 dark:border-slate-700">
                    <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2">Detalles de la Solicitud</h2>
                    <p class="text-sm text-slate-600 dark:text-slate-400 mb-6">Selecciona las fechas y proporciona información adicional.</p>

                    <Form 
                        ref="formRef"
                        :form="form"
                        @submit="submit"
                    />
                </div>
            </div>

            <!-- Resumen - Columna derecha (1/3) -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 dark:bg-slate-800 dark:border-slate-700">
                    <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">Resumen de Solicitud</h3>
                    <p class="text-sm text-slate-600 dark:text-slate-400 mb-6">Revisa los detalles antes de enviar.</p>

                    <!-- Días disponibles -->
                    <div class="text-center mb-6 p-4 bg-slate-50 rounded-lg dark:bg-slate-700/50">
                        <div class="text-3xl font-bold text-slate-900 dark:text-slate-100">{{ availableDays }}</div>
                        <div class="text-sm text-slate-600 dark:text-slate-400">Días Disponibles</div>
                    </div>

                    <!-- Detalles de períodos -->
                    <div v-if="periodsWithData.length > 0" class="space-y-4 mb-6">
                        <div v-for="(period, index) in periodsWithData" :key="index" class="space-y-2">
                            <h4 class="font-medium text-slate-900 dark:text-slate-100">
                                Período {{ index + 1 }}:
                            </h4>
                            <div class="space-y-1 text-sm text-slate-600 dark:text-slate-400">
                                <div>Inicio: {{ period.start_date }}</div>
                                <div>Fin: {{ period.end_date }}</div>
                                <div class="flex items-center gap-2">
                                    <span>Días en período {{ index + 1 }}:</span>
                                    <span class="px-2 py-1 bg-slate-100 text-slate-700 rounded-full text-xs font-medium dark:bg-slate-600 dark:text-slate-300">
                                        {{ period.number_of_days }} día{{ period.number_of_days > 1 ? 's' : '' }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Resumen de días -->
                    <div v-if="totalSelectedDays > 0" class="space-y-3 mb-6">
                        <div class="flex items-center justify-between">
                            <span class="text-sm text-slate-600 dark:text-slate-400">Total de días:</span>
                            <span class="px-2 py-1 bg-slate-100 text-slate-700 rounded-full text-xs font-medium dark:bg-slate-600 dark:text-slate-300">
                                {{ totalSelectedDays }} día{{ totalSelectedDays > 1 ? 's' : '' }}
                            </span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-sm text-slate-600 dark:text-slate-400">Días restantes:</span>
                            <span class="px-2 py-1 rounded-full text-xs font-medium"
                                  :class="remainingDays < 0 ? 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400' : 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400'">
                                {{ remainingDays }} día{{ remainingDays !== 1 ? 's' : '' }}
                            </span>
                        </div>
                    </div>

                    <!-- Advertencia si se excede el límite -->
                    <div v-if="remainingDays < 0" class="mb-6 p-3 bg-red-50 border border-red-200 rounded-lg dark:bg-red-500/10 dark:border-red-500/20">
                        <div class="flex items-center gap-2">
                            <GoogleIcon name="warning" class="w-4 h-4 text-red-600 dark:text-red-400" />
                            <span class="text-sm text-red-600 dark:text-red-400 font-medium">
                                Excedes tus días disponibles por {{ Math.abs(remainingDays) }} día{{ Math.abs(remainingDays) > 1 ? 's' : '' }}
                            </span>
                        </div>
                    </div>

                    <!-- Recordatorios -->
                    <div class="space-y-3">
                        <h4 class="font-medium text-slate-900 dark:text-slate-100">Recordatorios:</h4>
                        <div class="space-y-2 text-sm text-slate-600 dark:text-slate-400">
                            <div class="flex items-start gap-2">
                                <div class="w-1.5 h-1.5 bg-slate-400 rounded-full mt-2 flex-shrink-0"></div>
                                <span>Las solicitudes deben hacerse con 15 días de anticipación</span>
                            </div>
                            <div class="flex items-start gap-2">
                                <div class="w-1.5 h-1.5 bg-slate-400 rounded-full mt-2 flex-shrink-0"></div>
                                <span>Tu coordinador revisará y aprobará la solicitud</span>
                            </div>
                            <div class="flex items-start gap-2">
                                <div class="w-1.5 h-1.5 bg-slate-400 rounded-full mt-2 flex-shrink-0"></div>
                                <span>Recibirás una notificación con la decisión</span>
                            </div>
                            <div class="flex items-start gap-2">
                                <div class="w-1.5 h-1.5 bg-slate-400 rounded-full mt-2 flex-shrink-0"></div>
                                <span>Los días se descontarán una vez aprobados</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>