<script setup>
import SupervisorLayout from '@/Layouts/SupervisorLayout.vue';
import OutlineSelect from '@/Components/Supervisor/OutlineSelect.vue';
import {Head, Link, router, usePage} from '@inertiajs/vue3';
import {computed, ref, watch} from 'vue';

const props = defineProps({
    kpis: {
        type: Object,
        required: true,
    },
    alerts: {
        type: Array,
        default: () => [],
    },
    machinesOverview: {
        type: Array,
        default: () => [],
    },
    machineStatusBreakdown: {
        type: Object,
        default: () => ({}),
    },
    recentWashes: {
        type: Array,
        default: () => [],
    },
    context: {
        type: Object,
        default: () => ({}),
    },
    establishments: {
        type: Array,
        default: () => [],
    },
    showEstablishmentFilter: {
        type: Boolean,
        default: false,
    },
    filters: {
        type: Object,
        default: () => ({}),
    },
});

const page = usePage();
const supervisor = computed(() => page.props.auth.supervisor);

const greeting = computed(() => {
    const hour = new Date().getHours();
    if (hour < 12) return 'Bonjour';
    if (hour < 18) return 'Bon après-midi';
    return 'Bonsoir';
});

const todayLabel = computed(() => {
    const formatted = new Intl.DateTimeFormat('fr-FR', {
        weekday: 'long',
        day: 'numeric',
        month: 'long',
    }).format(new Date());

    return formatted.charAt(0).toUpperCase() + formatted.slice(1);
});

const firstName = computed(() => supervisor.value?.name?.split(' ')[0] ?? '');

const scopeTitle = computed(() => {
    if (props.context.is_all_establishments) {
        return 'Toutes les enseignes';
    }

    return props.context.establishment_name ?? 'Enseigne sélectionnée';
});

const establishmentOptions = computed(() => [
    { value: '', label: 'Toutes les enseignes' },
    ...props.establishments.map((establishment) => ({
        value: establishment.id,
        label: establishment.name,
    })),
]);

const selectedEstablishmentId = ref(props.filters.establishment_id ?? '');

watch(
    () => props.filters.establishment_id,
    (value) => {
        selectedEstablishmentId.value = value ?? '';
    },
);

const onEstablishmentChange = () => {
    router.get(
        route('supervisor.dashboard'),
        {
            establishment_id: selectedEstablishmentId.value || undefined,
        },
        {
            preserveScroll: true,
            replace: true,
        },
    );
};

const formatCurrency = (value) =>
    new Intl.NumberFormat('fr-FR', {style: 'currency', currency: 'EUR'}).format(value ?? 0);

const formatDate = (iso) => {
    if (!iso) return '—';
    return new Intl.DateTimeFormat('fr-FR', {
        dateStyle: 'short',
        timeStyle: 'short',
    }).format(new Date(iso));
};

const statusColor = (status) => {
    const colors = {
        available: 'bg-emerald-100 text-emerald-800 ring-emerald-600/20',
        reserved: 'bg-amber-100 text-amber-800 ring-amber-600/20',
        running: 'bg-sky-100 text-sky-800 ring-sky-600/20',
        maintenance: 'bg-orange-100 text-orange-800 ring-orange-600/20',
        offline: 'bg-slate-100 text-slate-600 ring-slate-500/20',
        error: 'bg-red-100 text-red-800 ring-red-600/20',
        pending_start: 'bg-slate-100 text-slate-600 ring-slate-500/20',
        completed: 'bg-emerald-100 text-emerald-800 ring-emerald-600/20',
        failed: 'bg-red-100 text-red-800 ring-red-600/20',
        cancelled: 'bg-slate-100 text-slate-500 ring-slate-500/20',
    };
    return colors[status] ?? 'bg-slate-100 text-slate-800';
};

const statusDotColor = (status) => {
    const colors = {
        available: 'bg-emerald-500',
        reserved: 'bg-amber-500',
        running: 'bg-sky-500',
        maintenance: 'bg-orange-500',
        offline: 'bg-slate-400',
        error: 'bg-red-500',
    };
    return colors[status] ?? 'bg-slate-400';
};

const severityColor = (severity) => {
    return severity === 'high'
        ? 'border-red-400 bg-red-50 ring-red-100'
        : 'border-amber-400 bg-amber-50 ring-amber-100';
};

const machineAnomalyCount = computed(() => {
    const breakdown = props.machineStatusBreakdown;
    return (breakdown.offline ?? 0) + (breakdown.maintenance ?? 0) + (breakdown.error ?? 0);
});

const kpiCards = computed(() => {
    const hasMachineAnomaly = machineAnomalyCount.value > 0;

    return [
        {
            label: "Chiffre d'affaires",
            sublabel: "Aujourd'hui",
            value: formatCurrency(props.kpis.revenue_today),
            icon: 'revenue',
            bg: 'bg-emerald-50',
            text: 'text-emerald-600',
            ring: 'ring-emerald-100',
        },
        {
            label: 'Lavages',
            sublabel: "Aujourd'hui",
            value: props.kpis.washes_today,
            icon: 'washes',
            bg: 'bg-sky-50',
            text: 'text-sky-600',
            ring: 'ring-sky-100',
        },
        {
            label: 'Réservations',
            sublabel: "Aujourd'hui",
            value: props.kpis.bookings_today,
            icon: 'bookings',
            bg: 'bg-violet-50',
            text: 'text-violet-600',
            ring: 'ring-violet-100',
        },
        {
            label: 'Machines actives',
            sublabel: `${props.kpis.running_machines ?? 0} en cours · ${props.kpis.available_machines ?? 0} dispo.`,
            value: `${props.kpis.machines_total - machineAnomalyCount.value}`,
            suffix: `/ ${props.kpis.machines_total}`,
            icon: 'machines',
            bg: hasMachineAnomaly ? 'bg-red-50' : 'bg-indigo-50',
            text: hasMachineAnomaly ? 'text-red-600' : 'text-indigo-600',
            ring: hasMachineAnomaly ? 'ring-red-100' : 'ring-indigo-100',
            alert: hasMachineAnomaly ? `${machineAnomalyCount.value} indisponible${machineAnomalyCount.value > 1 ? 's' : ''}` : null,
        },
    ];
});

const statusBreakdownItems = computed(() => {
    const labels = {
        available: 'Disponibles',
        reserved: 'Réservées',
        running: 'En cours',
        maintenance: 'Maintenance',
        offline: 'Hors ligne',
        error: 'Erreur',
    };
    const total = props.kpis.machines_total || 1;

    return Object.entries(props.machineStatusBreakdown)
        .filter(([, count]) => count > 0)
        .map(([status, count]) => ({
            status,
            label: labels[status] ?? status,
            count,
            percent: Math.round((count / total) * 100),
        }))
        .sort((a, b) => b.count - a.count);
});

const quickActions = [
    {
        label: 'Voir les machines',
        route: 'supervisor.machines.index',
        icon: 'machines',
        color: 'hover:border-indigo-300 hover:bg-indigo-50'
    },
    {
        label: 'Réservations du jour',
        route: 'supervisor.bookings.index',
        icon: 'bookings',
        color: 'hover:border-violet-300 hover:bg-violet-50'
    },
    {
        label: 'Historique lavages',
        route: 'supervisor.washes.index',
        icon: 'washes',
        color: 'hover:border-sky-300 hover:bg-sky-50'
    },
    {
        label: 'Gérer les tarifs',
        route: 'supervisor.pricing.index',
        icon: 'pricing',
        color: 'hover:border-emerald-300 hover:bg-emerald-50'
    },
];

const kpiIconPaths = {
    revenue: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z',
    washes: 'M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z',
    bookings: 'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z',
    machines: 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
    pricing: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z',
};
</script>

<template>
    <Head title="Tableau de bord"/>

    <SupervisorLayout>
        <template #header>
            <span class="hidden text-sm text-slate-400 sm:inline">/</span>
            <span class="hidden text-sm text-slate-500 sm:inline">Tableau de bord</span>
        </template>

        <!-- Welcome banner -->
        <div
            class="relative overflow-visible rounded-2xl border border-indigo-500/20 bg-gradient-to-br from-slate-900 via-indigo-950 to-indigo-900 shadow-xl shadow-indigo-950/20">
            <!-- Décorations (clipées sans couper le sélecteur) -->
            <div class="pointer-events-none absolute inset-0 overflow-hidden rounded-2xl">
                <div
                    class="absolute inset-0 opacity-[0.35]"
                    style="background-image: radial-gradient(circle at 1px 1px, rgb(255 255 255 / 0.08) 1px, transparent 0); background-size: 24px 24px;"
                />
                <div class="absolute -right-16 -top-16 h-56 w-56 rounded-full bg-indigo-500/25 blur-3xl"/>
                <div class="absolute -bottom-20 -left-10 h-48 w-48 rounded-full bg-violet-600/20 blur-3xl"/>
            </div>

            <div class="relative flex flex-col gap-6 p-6 sm:p-8 lg:flex-row lg:items-center lg:justify-between">
                <div class="flex min-w-0 items-start gap-4 sm:gap-5">
                    <div class="min-w-0">
                        <p class="inline-flex items-center rounded-full bg-white/10 px-3 py-1 text-xs font-medium text-indigo-200 ring-1 ring-white/10">
                            {{ todayLabel }}
                        </p>

                        <h2 class="mt-3 text-2xl font-bold tracking-tight text-white sm:text-3xl">
                            {{ greeting }}<span v-if="firstName">, {{ firstName }}</span>
                        </h2>

                        <div class="mt-4 flex flex-wrap items-center gap-2">
                            <span
                                class="inline-flex items-center gap-2 rounded-xl bg-white/10 px-3 py-1.5 text-sm font-medium text-white ring-1 ring-white/10">
                                <svg class="h-4 w-4 shrink-0 text-indigo-300" fill="none" viewBox="0 0 24 24"
                                     stroke="currentColor" stroke-width="1.75">
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z"/>
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z"/>
                                </svg>
                                <span class="truncate">{{ scopeTitle }}</span>
                            </span>

                            <span
                                v-if="kpis.active_bookings > 0"
                                class="inline-flex items-center gap-1.5 rounded-xl bg-amber-400/15 px-3 py-1.5 text-sm font-medium text-amber-100 ring-1 ring-amber-300/20"
                            >
                                <span class="h-1.5 w-1.5 animate-pulse rounded-full bg-amber-300"/>
                                {{ kpis.active_bookings }} réservation{{ kpis.active_bookings > 1 ? 's' : '' }} en cours
                            </span>
                        </div>
                    </div>
                </div>

                <div v-if="showEstablishmentFilter" class="relative z-20 w-full shrink-0 lg:w-72">
                    <OutlineSelect
                        id="dashboard-establishment"
                        v-model="selectedEstablishmentId"
                        :options="establishmentOptions"
                        variant="dark"
                        @change="onEstablishmentChange"
                    />
                </div>
            </div>
        </div>

        <!-- KPI cards -->
        <div class="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <div
                v-for="card in kpiCards"
                :key="card.label"
                class="rounded-2xl border border-slate-200/80 bg-white p-4 shadow-sm transition hover:shadow-md sm:p-5"
            >
                <div class="flex items-center gap-4">
                    <!-- Icône à gauche -->
                    <div
                        class="flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-2xl ring-4"
                        :class="[card.bg, card.ring]"
                    >
                        <svg
                            class="h-7 w-7"
                            :class="card.text"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                            stroke-width="1.75"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                :d="kpiIconPaths[card.icon]"
                            />
                        </svg>
                    </div>

                    <!-- Chiffres à droite -->
                    <div class="min-w-0 flex-1 text-right">
                        <p class="text-sm font-medium text-slate-500">{{ card.label }}</p>
                        <p class="mt-0.5 flex items-baseline justify-end gap-1">
                            <span class="text-2xl font-bold tracking-tight text-slate-900">{{ card.value }}</span>
                            <span v-if="card.suffix" class="text-base font-normal text-slate-400">{{
                                    card.suffix
                                }}</span>
                        </p>
                        <p class="mt-0.5 text-xs text-slate-400">{{ card.sublabel }}</p>
                        <p
                            v-if="card.alert"
                            class="mt-1.5 inline-flex items-center gap-1 rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700"
                        >
                            <span class="h-1.5 w-1.5 rounded-full bg-red-500"/>
                            {{ card.alert }}
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick actions -->
        <div class="mt-6">
            <h3 class="mb-3 text-sm font-semibold uppercase tracking-wider text-slate-400">Accès rapides</h3>
            <div class="grid grid-cols-2 gap-3 sm:grid-cols-4">
                <Link
                    v-for="action in quickActions"
                    :key="action.route"
                    :href="route(action.route)"
                    class="flex items-center gap-3 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-medium text-slate-700 shadow-sm transition"
                    :class="action.color"
                >
                    <svg class="h-4 w-4 flex-shrink-0 text-slate-400" fill="none" viewBox="0 0 24 24"
                         stroke="currentColor" stroke-width="1.75">
                        <path stroke-linecap="round" stroke-linejoin="round" :d="kpiIconPaths[action.icon]"/>
                    </svg>
                    {{ action.label }}
                </Link>
            </div>
        </div>

        <div class="mt-8 grid grid-cols-1 gap-6 lg:grid-cols-3">
            <!-- Machine status breakdown -->
            <div class="rounded-2xl border border-slate-200/80 bg-white p-5 shadow-sm lg:col-span-1">
                <h2 class="text-base font-semibold text-slate-900">État du parc</h2>
                <p class="mt-0.5 text-sm text-slate-500">{{ kpis.machines_total }}
                    machine{{ kpis.machines_total > 1 ? 's' : '' }} au total</p>

                <div v-if="statusBreakdownItems.length === 0" class="mt-6 text-sm text-slate-400">
                    Aucune machine dans votre périmètre.
                </div>
                <div v-else class="mt-5 space-y-3">
                    <div v-for="item in statusBreakdownItems" :key="item.status">
                        <div class="mb-1 flex items-center justify-between text-sm">
                            <span class="flex items-center gap-2 text-slate-600">
                                <span class="h-2 w-2 rounded-full" :class="statusDotColor(item.status)"/>
                                {{ item.label }}
                            </span>
                            <span class="font-medium text-slate-900">{{ item.count }}</span>
                        </div>
                        <div class="h-2 overflow-hidden rounded-full bg-slate-100">
                            <div
                                class="h-full rounded-full transition-all duration-500"
                                :class="statusDotColor(item.status)"
                                :style="{ width: `${item.percent}%` }"
                            />
                        </div>
                    </div>
                </div>
            </div>

            <!-- Alerts -->
            <div class="rounded-2xl border border-slate-200/80 bg-white p-5 shadow-sm lg:col-span-1">
                <div class="flex items-center justify-between">
                    <h2 class="text-base font-semibold text-slate-900">Alertes</h2>
                    <span
                        v-if="alerts.length > 0"
                        class="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700"
                    >
                        {{ alerts.length }}
                    </span>
                </div>

                <div v-if="alerts.length === 0" class="mt-8 flex flex-col items-center py-4 text-center">
                    <div class="flex h-12 w-12 items-center justify-center rounded-full bg-emerald-50">
                        <svg class="h-6 w-6 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"
                             stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>
                        </svg>
                    </div>
                    <p class="mt-3 text-sm font-medium text-slate-600">Tout va bien</p>
                    <p class="mt-1 text-xs text-slate-400">Aucune alerte pour le moment.</p>
                </div>
                <ul v-else class="mt-4 max-h-72 space-y-2 overflow-y-auto">
                    <li
                        v-for="(alert, index) in alerts"
                        :key="index"
                        class="rounded-xl border-l-4 px-3 py-2.5 text-sm ring-1 ring-inset"
                        :class="severityColor(alert.severity)"
                    >
                        <p class="font-medium text-slate-800">{{ alert.message }}</p>
                        <p class="mt-1 text-xs text-slate-500">{{ formatDate(alert.occurred_at) }}</p>
                    </li>
                </ul>
            </div>

            <!-- Recent washes -->
            <div class="rounded-2xl border border-slate-200/80 bg-white p-5 shadow-sm lg:col-span-1">
                <div class="flex items-center justify-between">
                    <h2 class="text-base font-semibold text-slate-900">Derniers lavages</h2>
                    <Link
                        :href="route('supervisor.washes.index')"
                        class="text-xs font-medium text-indigo-600 hover:text-indigo-800"
                    >
                        Tout voir →
                    </Link>
                </div>

                <div v-if="recentWashes.length === 0" class="mt-6 text-sm text-slate-400">
                    Aucun lavage récent.
                </div>
                <ul v-else class="mt-4 divide-y divide-slate-100">
                    <li
                        v-for="wash in recentWashes"
                        :key="wash.uuid"
                        class="flex items-center justify-between py-3 first:pt-0"
                    >
                        <div class="min-w-0">
                            <p class="truncate text-sm font-medium text-slate-800">{{ wash.machine_name }}</p>
                            <p class="truncate text-xs text-slate-400">
                                {{ wash.establishment_name }} · {{ formatDate(wash.started_at) }}
                            </p>
                        </div>
                        <div class="ml-3 flex-shrink-0 text-right">
                            <p class="text-sm font-semibold text-slate-900">{{ formatCurrency(wash.cost) }}</p>
                            <span
                                class="mt-0.5 inline-block rounded-full px-2 py-0.5 text-[10px] font-medium ring-1 ring-inset"
                                :class="statusColor(wash.status)"
                            >
                                {{ wash.status_label }}
                            </span>
                        </div>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Machines overview -->
        <div class="mt-6 rounded-2xl border border-slate-200/80 bg-white p-5 shadow-sm">
            <div class="mb-4 flex items-center justify-between">
                <div>
                    <h2 class="text-base font-semibold text-slate-900">Parc machines</h2>
                    <p class="mt-0.5 text-sm text-slate-500">Aperçu en temps réel de vos équipements</p>
                </div>
                <Link
                    :href="route('supervisor.machines.index')"
                    class="rounded-lg bg-indigo-50 px-3 py-1.5 text-sm font-medium text-indigo-700 transition hover:bg-indigo-100"
                >
                    Gérer le parc →
                </Link>
            </div>

            <div v-if="machinesOverview.length === 0" class="py-8 text-center text-sm text-slate-400">
                Aucune machine dans votre périmètre.
            </div>
            <div v-else class="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">
                <Link
                    v-for="machine in machinesOverview"
                    :key="machine.uuid"
                    :href="route('supervisor.machines.show', machine.uuid)"
                    class="group flex items-center gap-3 rounded-xl border border-slate-200 p-4 transition hover:border-indigo-200 hover:bg-indigo-50/30 hover:shadow-sm"
                >
                    <div
                        class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-slate-100 transition group-hover:bg-white"
                    >
                        <span class="h-2.5 w-2.5 rounded-full" :class="statusDotColor(machine.status)"/>
                    </div>
                    <div class="min-w-0 flex-1">
                        <p class="truncate text-sm font-medium text-slate-800 group-hover:text-indigo-700">
                            {{ machine.name }}
                        </p>
                        <p class="truncate text-xs text-slate-400">
                            {{ machine.establishment_name }} · {{ machine.type_label }}
                        </p>
                    </div>
                    <span
                        class="flex-shrink-0 rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset"
                        :class="statusColor(machine.status)"
                    >
                        {{ machine.status_label }}
                    </span>
                </Link>
            </div>
        </div>
    </SupervisorLayout>
</template>
