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

import GoogleIcon from '@Shared/GoogleIcon.vue';
import VueApexCharts from 'vue3-apexcharts';

// Propiedades
const adminInfo       = ref({});
const vacationsCharts = ref({});

// Opciones para gráfica de solicitudes por mes (línea)
const lineChartOptions = computed(() => ({
    chart: {
        type: 'line',
        height: 350,
        toolbar: {
            show: true
        },
        zoom: {
            enabled: true
        }
    },
    colors: ['#3B82F6'],
    stroke: {
        curve: 'smooth',
        width: 3
    },
    markers: {
        size: 6,
        hover: {
            size: 8
        }
    },
    xaxis: {
        categories: vacationsCharts.value.requests_by_month?.map(item => item.month_name) || [],
        title: {
            text: 'Mes'
        }
    },
    yaxis: {
        title: {
            text: 'Número de Solicitudes'
        },
        min: 0
    },
    tooltip: {
        y: {
            formatter: function (val) {
                return val + " solicitudes"
            }
        }
    },
    grid: {
        borderColor: '#f1f1f1'
    }
}));

// Series para gráfica de solicitudes por mes
const lineChartSeries = computed(() => [{
    name: 'Solicitudes',
    data: vacationsCharts.value.requests_by_month?.map(item => item.total_requests) || []
}]);

// Opciones para gráfica de solicitudes por departamento (donut)
const donutChartOptions = computed(() => ({
    chart: {
        type: 'donut',
        height: 350
    },
    colors: ['#3B82F6', '#8B5CF6', '#06B6D4', '#10B981', '#F59E0B', '#EF4444', '#EC4899', '#84CC16'],
    labels: vacationsCharts.value.requests_by_department?.map(item => item.department_name) || [],
    legend: {
        position: 'bottom',
        horizontalAlign: 'center'
    },
    plotOptions: {
        pie: {
            donut: {
                size: '70%',
                labels: {
                    show: true,
                    name: {
                        show: true,
                        fontSize: '14px',
                        fontWeight: 600
                    },
                    value: {
                        show: true,
                        fontSize: '16px',
                        fontWeight: 700,
                        formatter: function (val) {
                            return val + " solicitudes"
                        }
                    },
                    total: {
                        show: true,
                        showAlways: false,
                        label: 'Total',
                        fontSize: '16px',
                        fontWeight: 700,
                        color: '#373d3f',
                        formatter: function (w) {
                            return w.globals.seriesTotals.reduce((a, b) => {
                                return a + b
                            }, 0) + " solicitudes"
                        }
                    }
                }
            }
        }
    },
    tooltip: {
        y: {
            formatter: function (val) {
                return val + " solicitudes"
            }
        }
    },
    responsive: [{
        breakpoint: 480,
        options: {
            chart: {
                width: 200
            },
            legend: {
                position: 'bottom'
            }
        }
    }]
}));

// Series para gráfica de solicitudes por departamento
const donutChartSeries = computed(() => 
    vacationsCharts.value.requests_by_department?.map(item => item.total_requests) || []
);

/** Ciclos */
onMounted(() => {
    api.get(apiTo('admin'), {
        onSuccess: (r) => {
            adminInfo.value = r.admin_info;
            vacationsCharts.value = r.admin_info.charts;
        }
    });
});
</script>

<template>
    <div>
        <!-- Banner de bienvenida -->
        <section
            class="relative mb-8 overflow-hidden rounded-2xl bg-gradient-to-r from-indigo-600 to-purple-600 text-white"
        >
            <div class="relative z-10 p-6 md:p-8">
                <p class="text-2xl md:text-3xl font-semibold">
                    Bienvenido, {{ $page.user.name }}
                </p>
                <p class="mt-2 text-white/90">
                    Administra el sistema de vacaciones y supervisa el rendimiento organizacional.
                </p>
            </div>
        </section>

        <!-- Tarjetas de KPIs -->
        <section class="mb-8 grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-4">
            <!-- Total Empleados -->
            <article class="rounded-xl bg-white p-6 shadow with-transition hover:shadow-lg dark:bg-slate-800">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-4">
                        <GoogleIcon name="group" class="text-blue-500 text-5xl" />
                        <div>
                            <h3 class="text-sm text-slate-500 dark:text-slate-400">Total Empleados</h3>
                            <p class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ adminInfo.total_users }}</p>
                        </div>
                    </div>
                </div>
            </article>

            <!-- Solicitudes Este Mes -->
            <article class="rounded-xl bg-white p-6 shadow with-transition hover:shadow-lg dark:bg-slate-800">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-4">
                        <GoogleIcon name="description" class="text-blue-500 text-5xl" />
                        <div>
                            <h3 class="text-sm text-slate-500 dark:text-slate-400">Solicitudes Este Mes</h3>
                            <p class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ adminInfo.monthly_requests }}</p>
                        </div>
                    </div>
                </div>
            </article>

            <!-- Solicitudes Aprobadas -->
            <article class="rounded-xl bg-white p-6 shadow with-transition hover:shadow-lg dark:bg-slate-800">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-4">
                        <GoogleIcon name="check_circle" class="text-emerald-500 text-5xl" />
                        <div>
                            <h3 class="text-sm text-slate-500 dark:text-slate-400">Solicitudes Aprobadas</h3>
                            <p class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ adminInfo.approved_requests }}</p>
                        </div>
                    </div>
                </div>
            </article>

            <!-- Eficiencia Aprobación -->
            <article class="rounded-xl bg-white p-6 shadow with-transition hover:shadow-lg dark:bg-slate-800">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-4">
                        <GoogleIcon name="trending_up" class="text-emerald-500 text-5xl" />
                        <div>
                            <h3 class="text-sm text-slate-500 dark:text-slate-400">Eficiencia Aprobación</h3>
                            <p class="text-2xl font-bold text-slate-900 dark:text-slate-100">{{ adminInfo.approval_efficiency }}%</p>
                        </div>
                    </div>
                </div>
            </article>
        </section>

        <!-- Gráficos -->
        <section v-if="vacationsCharts.requests_by_month && vacationsCharts.requests_by_department" class="grid grid-cols-1 gap-6 lg:grid-cols-2">
            <!-- Gráfico de Solicitudes por Mes -->
            <article class="rounded-xl bg-white p-6 shadow dark:bg-slate-800">
                <div class="mb-6 flex items-center gap-3">
                    <GoogleIcon name="trending_up" class="text-blue-500 text-2xl" />
                    <div>
                        <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100">Solicitudes por Mes</h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Tendencia de solicitudes durante el año</p>
                    </div>
                </div>
                
                <div class="h-80">
                    <VueApexCharts
                        type="line"
                        height="100%"
                        :options="lineChartOptions"
                        :series="lineChartSeries"
                    />
                </div>
            </article>

            <!-- Gráfico de Solicitudes por Departamento -->
            <article class="rounded-xl bg-white p-6 shadow dark:bg-slate-800">
                <div class="mb-6 flex items-center gap-3">
                    <GoogleIcon name="pie_chart" class="text-purple-500 text-2xl" />
                    <div>
                        <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100">Solicitudes por Departamento</h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400">Distribución de solicitudes por área</p>
                    </div>
                </div>
                
                <div class="h-80">
                    <VueApexCharts
                        type="donut"
                        height="100%"
                        :options="donutChartOptions"
                        :series="donutChartSeries"
                    />
                </div>
            </article>
        </section>

        <!-- Estado vacío para charts -->
        <section v-else class="rounded-xl bg-white p-6 shadow dark:bg-slate-800">
            <div class="text-center py-12">
                <GoogleIcon name="analytics" class="text-slate-400 text-6xl mx-auto mb-4" />
                <h3 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2">
                    No hay datos de gráficos disponibles
                </h3>
                <p class="text-slate-500 dark:text-slate-400">
                    Los gráficos se mostrarán cuando haya datos de solicitudes disponibles.
                </p>
            </div>
        </section>
    </div>
</template>
