<script setup lang="ts">
import { ref, computed } from 'vue';
import { Head, Link } from '@inertiajs/vue3';
import AppLayout from "@/layouts/AppLayout.vue";
import type { BreadcrumbItem } from "@/types";

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Статистика монтажников',
        href: '/installers/stats',
    },
];

const props = defineProps(['installers']);

const sortKey = ref('name');
const sortAsc = ref(true);

const sortedInstallers = computed(() => {
    return [...props.installers].sort((a, b) => {
        let valA = a[sortKey.value];
        let valB = b[sortKey.value];

        // Обработка null/undefined
        if (valA == null) valA = sortKey.value === 'name' ? '' : -Infinity;
        if (valB == null) valB = sortKey.value === 'name' ? '' : -Infinity;

        // Если строки — сравниваем строками
        if (typeof valA === 'string' && typeof valB === 'string') {
            valA = valA.toLowerCase();
            valB = valB.toLowerCase();

            if (valA < valB) return sortAsc.value ? -1 : 1;
            if (valA > valB) return sortAsc.value ? 1 : -1;
            return 0;
        }

        // Если числа — числовое сравнение
        if (typeof valA === 'number' && typeof valB === 'number') {
            return sortAsc.value ? valA - valB : valB - valA;
        }

        // На всякий случай сравним как строки
        valA = String(valA);
        valB = String(valB);
        if (valA < valB) return sortAsc.value ? -1 : 1;
        if (valA > valB) return sortAsc.value ? 1 : -1;
        return 0;
    });
});

function sortBy(key: string) {
    if (sortKey.value === key) {
        sortAsc.value = !sortAsc.value;
    } else {
        sortKey.value = key;
        sortAsc.value = true;
    }
}

function formatHours(hours: number | null | undefined) {
    if (hours == null || isNaN(hours)) return '—';
    const h = Math.floor(hours);
    const m = Math.round((hours - h) * 60);
    return `${h}ч ${m}м`;
}
</script>

<template>
    <Head title="Статистика монтажников" />

    <AppLayout :breadcrumbs="breadcrumbs">
        <div class="flex h-full flex-1 flex-col gap-4 rounded-xl p-4">
            <h1 class="text-2xl font-bold mb-4">Статистика по монтажникам</h1>
            <table class="w-full text-sm text-left text-gray-700">
                <thead class="text-xs text-gray-500 uppercase bg-gray-50 border-b border-gray-200">
                <tr>
                    <th @click="sortBy('name')" class="px-4 py-3 cursor-pointer select-none">
                        <div class="flex items-center gap-1">
                            Имя
                            <span v-if="sortKey === 'name'">{{ sortAsc ? '▲' : '▼' }}</span>
                        </div>
                    </th>
                    <th @click="sortBy('ratings_received_avg')" class="px-4 py-3 cursor-pointer select-none">
                        <div class="flex items-center gap-1">
                            Рейтинг
                            <span v-if="sortKey === 'ratings_received_avg'">{{ sortAsc ? '▲' : '▼' }}</span>
                        </div>
                    </th>
                    <th @click="sortBy('completed_count')" class="px-4 py-3 cursor-pointer select-none">
                        <div class="flex items-center gap-1">
                            Завершено
                            <span v-if="sortKey === 'completed_count'">{{ sortAsc ? '▲' : '▼' }}</span>
                        </div>
                    </th>
                    <th @click="sortBy('rejected_count')" class="px-4 py-3 cursor-pointer select-none">
                        <div class="flex items-center gap-1">
                            Отказов
                            <span v-if="sortKey === 'rejected_count'">{{ sortAsc ? '▲' : '▼' }}</span>
                        </div>
                    </th>
                    <th @click="sortBy('avg_hours')" class="px-4 py-3 cursor-pointer select-none">
                        <div class="flex items-center gap-1">
                            Ср. время
                            <span v-if="sortKey === 'avg_hours'">{{ sortAsc ? '▲' : '▼' }}</span>
                        </div>
                    </th>
                </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                <tr
                    v-for="installer in sortedInstallers"
                    :key="installer.id"
                    class="hover:bg-gray-50 transition-colors"
                >
                    <td class="px-4 py-3 font-medium text-gray-800 whitespace-nowrap">
                        <Link :href="`/installers/${installer.id}`" class="text-blue-600 hover:underline">
                            {{ installer.name }}
                        </Link>
                    </td>
                    <td class="px-4 py-3">{{ installer.ratings_received_avg?.toFixed(1) ?? '—' }}</td>
                    <td class="px-4 py-3">{{ installer.completed_count }}</td>
                    <td class="px-4 py-3">{{ installer.rejected_count }}</td>
                    <td class="px-4 py-3">{{ formatHours(installer.avg_hours) }}</td>
                </tr>
                </tbody>
            </table>

        </div>
    </AppLayout>
</template>

<style scoped>
th {
    user-select: none;
}
</style>
