<script setup lang="ts">
import {ref, computed, watch, onBeforeUnmount, onMounted} from 'vue';
import {Link, usePage, router, Head} from '@inertiajs/vue3';
import AppLayout from "@/layouts/AppLayout.vue";
import type {BreadcrumbItem} from "@/types";
import {Toaster} from '@/components/ui/sonner';
import {toast} from 'vue-sonner';
import 'vue-sonner/style.css';
import {Calendar} from '@/components/ui/calendar'
import {Popover, PopoverTrigger, PopoverContent} from '@/components/ui/popover'
import {Button} from '@/components/ui/button'
import {CalendarIcon, ImageDown} from 'lucide-vue-next'
import {Input} from '@/components/ui/input'
import {format} from 'date-fns'
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select'
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip'
import {
    Pagination,
    PaginationContent,
    PaginationItem,
    PaginationPrevious,
    PaginationNext,
    PaginationEllipsis,
} from '@/components/ui/pagination'
import {
    Dialog,
    DialogContent,
    DialogOverlay,
} from '@/components/ui/dialog';
import {Textarea} from "@/components/ui/textarea";

const loading = ref(false);

const selectedImage = ref('');
const showImageModal = ref(false);
const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Панель управления', href: '/dashboard' },
    {title: 'Заявки', href: '/requests'},
]
const props = defineProps(['requests', 'filters', 'installers']);
const user = usePage().props.auth.user;
const requests = computed(() => props.requests.data);

const isAdmin = computed(() => user.role === 'admin');
const isEngineer = computed(() => user.role === 'engineer');
const isInstaller = computed(() => user.role === 'installer');

const commentInputs = ref<Record<number, string>>({});
const priceInputs = ref<Record<number, number | ''>>({});

const filterAddress = ref(props.filters.address || '');
const filterSearch = ref(props.filters.search || '');

const filterStatus = ref(props.filters.status || '');
const filterInstallerId = ref(props.filters.installer_id || '');
const filterDateFrom = ref(props.filters.date_from ? new Date(props.filters.date_from) : null);
const filterDateTo = ref(props.filters.date_to ? new Date(props.filters.date_to) : null);

const formatDate = (date: Date | null): string | null => date ? format(date, 'yyyy-MM-dd') : null;

const isImage = (path: string) => /\.(jpg|jpeg|png|gif|webp)$/i.test(path)

const isVideo = (path: string) => /\.(mp4|webm|mov|avi)$/i.test(path)

const selectedMedia = ref('')
const selectedMediaType = ref<'image' | 'video'>('image')

const modalVideo = ref<HTMLVideoElement | null>(null);

watch(selectedMedia, () => {
    // Останавливаем предыдущее видео перед установкой нового
    if (modalVideo.value) {
        modalVideo.value.pause();
        modalVideo.value.currentTime = 0;
        // Обновление источника произойдет автоматически через :src
    }
});

function applyFilters(overrides: Record<string, any> = {}) {
    loading.value = true;
    router.get('/requests', {
        status: filterStatus.value || undefined,
        installer_id: filterInstallerId.value || undefined,
        date_from: formatDateForAPI(filterDateFrom.value) || undefined,
        date_to: formatDateForAPI(filterDateTo.value) || undefined,
        search: filterSearch.value || undefined,
        ...overrides
    }, {
        preserveState: true,
        preserveScroll: true,
        replace: true,
        onFinish: () => {
            loading.value = false;
        }
    });
}

//watch([filterStatus, filterInstallerId, filterDateFrom, filterDateTo, filterAddress], applyFilters, {deep: true});
let timeout: ReturnType<typeof setTimeout>;

watch(
    [filterStatus, filterInstallerId, filterDateFrom, filterDateTo, filterSearch],
    () => {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            applyFilters();
        }, 400);
    }
);

function goToPage(page: number) {
    if (page === props.requests.current_page) return;
    if (page < 1 || page > props.requests.last_page) return;
    applyFilters({page});
}

function resetFilters() {
    filterStatus.value = '';
    filterInstallerId.value = '';
    filterDateFrom.value = null;
    filterDateTo.value = null;
    filterSearch.value = '';
}

function rejectRequest(id: number) {
    if (confirm('Вы уверены?')) {
        router.post(`/requests/${id}/reject`, {}, {
            onSuccess: () => {
                const r = requests.value.find(r => r.id === id);
                if (r) {
                    r.status = 'cancelled';
                    r.assigned_to = null;
                }
            },
            onError: () => toast.error('Не удалось отклонить заявку')
        });
    }
}

function takeRequest(id: number) {
    if (confirm('Взять заявку в работу?')) {
        router.post(`/requests/${id}/assign`, {}, {
            preserveScroll: true,
            replace: true,
            onSuccess: () => {
                const r = requests.value.find(r => r.id === id);
                if (r) {
                    r.status = 'assigned';
                    r.assigned_to = user.id;
                }
                toast.success(`Вы взяли в работу заявку #${id}`);
            },
            onError: () => toast.error('Не удалось взять заявку в работу')
        });
    }
}

function completeRequest(id: number) {
    const note = commentInputs.value[id] || '';
    const installation_price = priceInputs.value[id] || null;

    router.post(`/requests/${id}/complete`, {note, installation_price}, {
        preserveScroll: true,
        onSuccess: () => {
            const r = requests.value.find(r => r.id === id);
            if (r) r.status = 'done';
            commentInputs.value[id] = '';
            priceInputs.value[id] = '';
            toast.success(`Вы завершили заявку #${id}`);
        },
        onError: () => toast.error('Ошибка при завершении заявки')
    });
}

function deleteRequest(id: number) {
    if (confirm('Удалить заявку? Это действие необратимо.')) {
        router.delete(`/requests/${id}`, {
            onSuccess: () => {
                const index = requests.value.findIndex(r => r.id === id);
                if (index !== -1) requests.value.splice(index, 1);
                toast.success('Заявка удалена');
            },
            onError: () => toast.error('Ошибка удаления')
        });
    }
}

const statusLabels: Record<string, string> = {
    new: 'Новая',
    assigned: 'Назначена',
    in_progress: 'В работе',
    done: 'Завершена',
    cancelled: 'Отменена',
};

function openMedia(path: string, cardVideo?: HTMLVideoElement) {
    if (cardVideo) {
        cardVideo.pause();
        cardVideo.currentTime = 0;
    }
    selectedMedia.value = `/storage/${path}`;
    selectedMediaType.value = path.match(/\.(mp4|mov|avi|webm)$/i) ? 'video' : 'image';
    showImageModal.value = true;
}

watch(showImageModal, (val) => {
    if (!val && modalVideo.value) {
        modalVideo.value.pause();
        modalVideo.value.currentTime = 0;
        modalVideo.value.src = ''; // полностью сбрасываем
    }
});

onMounted(() => {
    if (window.Echo) {
        window.Echo.private('requests')
            .listen('.InstallRequestAssigned', (e: any) => {
                toast.success(`Заявка #${e.id} назначена!`);
                updateRequest(e);
            })
            .listen('.InstallRequestCompleted', (e: any) => {
                toast.success(`Заявка #${e.id} завершена!`);
                updateRequest(e);
            })
            .listen('.InstallRequestRejected', (e: any) => {
                toast.success(`Заявка #${e.id} отклонена!`);
                updateRequest(e);
            });
    }
});

function updateRequest(updatedRequest: any) {
    const index = requests.value.findIndex(r => r.id === updatedRequest.id);
    if (index !== -1) {
        // Обновляем существующую заявку
        requests.value[index] = {...requests.value[index], ...updatedRequest};
    } else {
        // Если заявки нет, можно добавить (если надо)
        requests.value.unshift(updatedRequest);
    }
}

function exportXlsx() {
    const params = new URLSearchParams()

    if (filterStatus.value) params.append('status', filterStatus.value)
    if (filterInstallerId.value) params.append('installer_id', filterInstallerId.value)
    if (filterDateFrom.value) params.append('date_from', formatDateForAPI(filterDateFrom.value)!)
    if (filterDateTo.value) params.append('date_to', formatDateForAPI(filterDateTo.value)!)
    if (filterAddress.value) params.append('address', filterAddress.value)

    window.location.href = `/requests/export?${params.toString()}`
}

function exportExcel() {
    router.get('/requests/export', {
        status: filterStatus.value || undefined,
        installer_id: filterInstallerId.value || undefined,
        date_from: formatDateForAPI(filterDateFrom.value) || undefined,
        date_to: formatDateForAPI(filterDateTo.value) || undefined,
        address: filterAddress.value || undefined,
    }, {
        preserveState: true,
    });
}

// Функция форматирования для отправки на сервер (yyyy-MM-dd)
const formatDateForAPI = (date: Date | null): string | null =>
    date ? format(date, 'yyyy-MM-dd') : null;

// Функция форматирования для отображения (dd.MM.yyyy)
const formatDateForDisplay = (date: Date | null): string =>
    date ? format(date, 'dd.MM.yyyy HH:mm') : '';

function retryRequest(id: number) {
    router.post(`/requests/${id}/sync-1c`, {}, {
        preserveScroll: true,
        onSuccess: (page) => {
            // можно проверить, что пришло с бэка (если нужно)
            toast.success(`Заявка #${id} отправлена в 1С`);
        },
        onError: () => {
            toast.error(`Ошибка отправки заявки #${id} в 1С`);
        },
    });
}
function downloadMedia(id: number) {
    toast.info('Подготовка архива...')

    window.location.href = `/requests/${id}/download-media`
}
</script>

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

    <AppLayout :breadcrumbs="breadcrumbs">
        <div class="flex h-full flex-1 flex-col gap-4 rounded-xl pl-4 pb-4 pr-4">
            <Toaster/>

            <div>
                <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4 mb-6">
                    <h1 class="text-2xl font-bold">Заявки</h1>
                    <div class="flex flex-col sm:flex-row sm:items-center gap-3 w-full sm:w-auto">
                        <!-- Поиск по адресу -->
                        <div class="flex flex-col">
                            <Input
                                id="address"
                                type="text"
                                v-model="filterSearch"
                                placeholder="Поиск по адресу или телефону..."
                                class="w-full sm:w-64 rounded border px-3 py-2 text-sm text-gray-800"
                            />
                        </div>

                        <Link
                            v-if="user.role === 'admin' || user.role === 'engineer'"
                            href="/requests/create"
                            class="w-full sm:w-auto text-center inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive bg-primary text-primary-foreground shadow-xs hover:bg-primary/90 h-9 px-4 py-2 has-[>svg]:px-3"
                        >
                            Добавить заявку
                        </Link>
                    </div>
                </div>

                <div v-if="user.role === 'admin' || user.role === 'engineer'"
                     class="flex flex-col md:flex-row md:flex-wrap gap-4 mt-6 mb-6 items-center bg-gray-50 p-4 rounded-md border border-gray-200 sticky top-2 z-10 backdrop-blur">
                    <!-- Статус -->
                    <Select v-model="filterStatus" class="w-full md:w-48">
                        <SelectTrigger class="w-full md:w-48 cursor-pointer">
                            <SelectValue placeholder="Все статусы"/>
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectItem class="cursor-pointer" :value="null">Все статусы</SelectItem>
                                <SelectItem class="cursor-pointer" value="new">Новая</SelectItem>
                                <SelectItem class="cursor-pointer" value="assigned">Назначена</SelectItem>
                                <SelectItem class="cursor-pointer" value="in_progress">В работе</SelectItem>
                                <SelectItem class="cursor-pointer" value="done">Завершена</SelectItem>
                                <SelectItem class="cursor-pointer" value="cancelled">Отменена</SelectItem>
                            </SelectGroup>
                        </SelectContent>
                    </Select>

                    <!-- Монтажник (только для админа) -->
                    <Select v-if="user.role === 'admin' || user.role === 'engineer'" v-model="filterInstallerId"
                            class="w-full md:w-48">
                        <SelectTrigger class="w-full md:w-48 cursor-pointer">
                            <SelectValue placeholder="Все монтажники"/>
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectItem :value="null">Все монтажники</SelectItem>
                                <SelectItem
                                    v-for="installer in installers"
                                    :key="installer.id"
                                    :value="installer.id"
                                    class="cursor-pointer"
                                >
                                    {{ installer.name }}
                                </SelectItem>
                            </SelectGroup>
                        </SelectContent>
                    </Select>

                    <!-- Дата с -->
                    <Popover>
                        <PopoverTrigger as-child class="w-full md:w-40 justify-start text-left">
                            <Button variant="outline" class="w-full md:w-40 justify-start text-left font-normal cursor-pointer">
                                <CalendarIcon class="mr-2 h-4 w-4"/>
                                <span>
                                    {{ filterDateFrom ? formatDateForDisplay(filterDateFrom) : 'Выберите дату' }}
                                  </span>
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent class="w-auto p-0">
                            <Calendar v-model="filterDateFrom" :mode="'single'" :selected="filterDateFrom" locale="ru-RU" class="cursor-pointer" />
                        </PopoverContent>
                    </Popover>

                    <!-- Дата по -->
                    <Popover>
                        <PopoverTrigger as-child class="w-full md:w-40 justify-start text-left">
                            <Button variant="outline" class="w-full md:w-40 justify-start text-left font-normal cursor-pointer">
                                <CalendarIcon class="mr-2 h-4 w-4"/>
                                <span>
                                {{ filterDateTo ? formatDateForDisplay(filterDateTo) : 'Выберите дату' }}
                              </span>
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent class="w-auto p-0">
                            <Calendar v-model="filterDateTo" :mode="'single'" :selected="filterDateTo" locale="ru-RU" class="cursor-pointer" />
                        </PopoverContent>
                    </Popover>

                    <!-- Сброс фильтров -->
                    <Button
                        variant="outline"
                        class="ml-auto md:max-w-[140px] w-full cursor-pointer"
                        @click="resetFilters"
                    >
                        Сбросить фильтр
                    </Button>
                    <Button
                        variant="default"
                        class="md:max-w-[130px] w-full bg-green-600 hover:bg-green-900 cursor-pointer"
                        @click="exportXlsx"
                    >
                        Скачать Excel
                    </Button>
                </div>

                <div v-if="loading" class="flex justify-center my-8">
                    <svg class="animate-spin h-6 w-6 text-gray-600" xmlns="http://www.w3.org/2000/svg" fill="none"
                         viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                    </svg>
                </div>

                <!-- Нет заявок -->
                <div
                    v-else-if="!requests.length"
                    class="text-center text-gray-500 py-10 bg-white rounded-lg border border-gray-200 shadow-sm"
                >
                    <p class="text-lg font-medium">Заявок не найдено</p>
                    <p class="text-sm mt-1">Попробуйте изменить фильтры или сбросить их</p>
                </div>

                <div v-else>
                    <div
                        v-for="r in requests"
                        :key="r.id"
                        class="rounded-xl shadow-sm p-4 sm:p-6 mt-4 sm:mt-6 mb-4 sm:mb-6 bg-white border-l-4"
                        :class="{
                      'border-yellow-400': r.status === 'assigned',
                      'border-green-500': r.status === 'done',
                      'border-red-400': r.status === 'cancelled',
                      'border-gray-300': r.status === 'new' || r.status === 'in_progress',
                    }"
                    >
                        <div class="flex items-center justify-between mb-2">
                            <h2 class="text-xl font-semibold">{{ r.title }}</h2>
                            <div class="flex flex-col items-end">
                            <span
                                class="text-sm font-semibold"
                                :class="{
                                  'text-yellow-600': r.status === 'assigned',
                                  'text-green-600': r.status === 'done',
                                  'text-red-600': r.status === 'cancelled',
                                  'text-gray-500': r.status === 'new' || r.status === 'in_progress',
                                }"
                            >
                                {{ statusLabels[r.status] || r.status }}
                            </span>
                                <!-- Номер заявки -->
                                <span
                                    class="text-xs font-medium bg-gray-200 text-gray-800 px-2 py-0.5 rounded-full"
                                >
                          Заявка № {{ r.id }}
                        </span>
                            </div>
                        </div>

                        <div class="text-sm text-gray-700 space-y-4">

                            <!-- Блок с полями -->
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">

                                <div class="flex flex-col">
                                    <span class="text-xs uppercase text-gray-400 font-medium">Регион</span>
                                    <span class="font-medium">{{ r.region || '—' }}</span>
                                </div>

                                <div class="flex flex-col">
                                    <span class="text-xs uppercase text-gray-400 font-medium">Адрес</span>
                                    <span class="font-medium">{{ r.address }}</span>
                                </div>

                                <div class="flex flex-col">
                                    <span class="text-xs uppercase text-gray-400 font-medium">Дата установки</span>
                                    <span class="font-medium">{{
                                            r.scheduled_date ? formatDateForDisplay(new Date(r.scheduled_date)) : '—'
                                        }}</span>
                                </div>

                                <div class="flex flex-col">
                                    <span class="text-xs uppercase text-gray-400 font-medium">Субъект</span>
                                    <span class="font-medium">
        {{ r.subject && r.subject.trim() !== '' ? r.subject : '—' }}
      </span>
                                </div>

                                <div class="flex flex-col sm:col-span-2">
                                    <span class="text-xs uppercase text-gray-400 font-medium">Описание</span>
                                    <span class="font-medium">{{ r.description || '—' }}</span>
                                </div>

                                <div class="flex flex-col sm:col-span-2">
                                    <span
                                        class="text-xs uppercase text-gray-400 font-medium">Ответственный за монтаж</span>
                                    <span class="font-medium">{{ r.installer?.name || '—' }}</span>
                                </div>

                            </div>

                            <!-- Разделитель -->
                            <div class="border-t pt-4"></div>

                            <!-- Клиент -->
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div class="flex flex-col">
                                    <span class="text-xs uppercase text-gray-400 font-medium">Клиент</span>
                                    <span class="font-medium">{{
                                            r.client_name && r.client_name.trim() !== '' ? r.client_name : '—'
                                        }}</span>
                                </div>

                                <div class="flex flex-col">
                                    <span class="text-xs uppercase text-gray-400 font-medium">Телефон</span>
                                    <span class="font-medium text-blue-600 hover:underline">
                                    <a v-if="r.client_phone" :href="`tel:${r.client_phone}`">{{ r.client_phone }}</a>
                                    <span v-else>—</span>
                                </span>
                                </div>
                            </div>

                            <!-- Фото -->
                            <div v-if="r.photos?.length" class="pt-4">
                                <span class="flex items-center gap-3 text-xs uppercase text-gray-400 font-semibold mb-2">
                                    Медиа
                                </span>

                                <div class="flex flex-wrap gap-2">
                                    <div
                                        v-for="photo in r.photos"
                                        :key="photo.id"
                                        class="w-28 h-28"
                                        @click="openMedia(photo.path, $refs[`video-${photo.id}`])"
                                    >
                                        <!-- 📷 Фото -->
                                        <template v-if="isImage(photo.path)">
                                            <img
                                                :src="`/storage/${photo.path}`"
                                                class="w-full h-full rounded-lg object-cover border shadow-sm cursor-pointer hover:scale-[1.03] transition"
                                                @click="openMedia(photo.path)"
                                            />
                                        </template>

                                        <!-- 🎬 Видео -->
                                        <template v-else-if="isVideo(photo.path)">
                                            <div
                                                class="w-28 h-28 relative cursor-pointer"
                                                @click="openMedia(photo.path)"
                                            >
                                                <video
                                                    ref="`video-${photo.id}`"
                                                    :src="`/storage/${photo.path}`"
                                                    class="w-full h-full rounded-lg object-cover border shadow-sm"
                                                    controls
                                                    preload="metadata"
                                                    muted
                                                />
                                                <!-- Иконка Play поверх превью -->
                                                <div class="absolute inset-0 flex items-center justify-center">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-white/80 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-6.518-3.759A1 1 0 007 8.176v7.648a1 1 0 001.234.97l6.518-3.759a1 1 0 000-1.736z" />
                                                    </svg>
                                                </div>
                                            </div>
                                        </template>
                                    </div>
                                    <div class="shrink-0 flex items-center">
                                        <TooltipProvider>
                                            <Tooltip>
                                                <TooltipTrigger as-child>
                                                    <button
                                                        v-if="r.photos?.length"
                                                        type="button"
                                                        @click="downloadMedia(r.id)"
                                                        class="inline-flex items-center cursor-pointer"
                                                    >
                                                        <ImageDown />
                                                    </button>
                                                </TooltipTrigger>

                                                <TooltipContent
                                                    side="top"
                                                    align="center"
                                                    :side-offset="8"
                                                    class="z-50"
                                                >
                                                    <p>Скачать все фото и видео</p>
                                                </TooltipContent>
                                            </Tooltip>
                                        </TooltipProvider>
                                    </div>
                                </div>
                            </div>

                        </div>


                        <Dialog v-model:open="showImageModal">
                            <DialogOverlay class="bg-black/60 fixed inset-0"/>
                            <DialogContent class="bg-white p-0 rounded-xl w-full sm:max-w-[80%]">
                                <template v-if="selectedMediaType === 'image'">
                                    <img :src="selectedMedia" class="w-full max-h-[90vh] object-contain rounded-xl"/>
                                </template>
                                <template v-else>
                                    <video :src="selectedMedia" class="w-full max-h-[90vh] object-contain" controls />
                                </template>
                            </DialogContent>
                        </Dialog>

                        <div
                            v-if="user.role === 'installer' && (!r.assigned_to || r.status === 'new')"
                            class="mt-4"
                        >
                            <button
                                @click="takeRequest(r.id)"
                                class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm"
                            >
                                Взять в работу
                            </button>
                        </div>

                        <div
                            v-if="user.role === 'installer' && r.assigned_to === user.id && r.status === 'assigned'"
                            class="mt-4 flex flex-col gap-2"
                        >
                        <Textarea
                            v-model="commentInputs[r.id]"
                            placeholder="Комментарий при завершении"
                            class="w-full rounded border px-3 py-2 text-sm text-gray-800"
                            rows="3"
                        ></Textarea>

                            <Input
                                v-model="priceInputs[r.id]"
                                type="number"
                                step="0.01"
                                placeholder="Цена монтажа"
                                class="w-full sm:w-64 rounded border px-3 py-2 text-sm text-gray-800"
                            />

                            <Button
                                @click="completeRequest(r.id)"
                                class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded text-sm self-start"
                            >
                                Завершить
                            </Button>
                        </div>

                        <div
                            v-if="
                              (user.role === 'admin' || user.role === 'engineer')
                            "
                            class="mt-3 space-y-2"
                        >
                            <!--
                            <Link
                                :href="`/requests/${r.id}/rate`"
                                class="text-blue-600 underline text-sm hover:text-blue-800"
                            >
                                Оценить монтажника
                            </Link>-->

                            <!-- 💰 Стоимость монтажа -->
                            <div
                                v-if="r.actions && r.actions.length && r.actions[0].installation_price !== null"
                                class="mt-4 p-4 rounded-xl border bg-amber-50 border-amber-200/70 shadow-sm flex items-start gap-3"
                            >
                                <div
                                    class="flex items-center justify-center w-10 h-10 rounded-lg bg-amber-100 text-amber-600">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none"
                                         viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                              d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8V4m0 12v4"/>
                                    </svg>
                                </div>

                                <div>
                                    <div class="text-xs uppercase text-amber-700 font-semibold tracking-wide">
                                        Стоимость монтажа
                                    </div>
                                    <div
                                        class="mt-1 text-lg font-semibold text-amber-900 flex items-baseline"
                                        v-html="
                                        (() => {
                                            const formatted = Number(r.actions[0].installation_price)
                                                .toLocaleString('ru-RU', {
                                                    minimumFractionDigits: 2,
                                                    maximumFractionDigits: 2
                                                })
                                                .replace(',', '.'); // замена , на .

                                            const match = formatted.match(/(\d+)\.(\d{2})/);

                                            if (!match) return formatted + ' BYN';

                                            const amount = match[1];
                                            const cents = match[2];

                                            return `
                                                ${amount}.
                                                <span class='text-xs align-super leading-none ml-0.5'>${cents}</span>
                                                <span class='ml-1 text-sm text-amber-700 font-medium'>BYN</span>
                                            `;
                                        })()
                                    "
                                    ></div>
                                </div>
                            </div>

                            <!-- 📝 Комментарий монтажника -->
                            <div
                                v-if="r.actions?.some(a => a.action === 'completed' && a.note)"
                                class="mt-4 p-4 rounded-xl border bg-emerald-50 border-emerald-200/70 shadow-sm flex items-start gap-3"
                            >
                                <div
                                    class="flex items-center justify-center w-10 h-10 rounded-lg bg-emerald-100 text-emerald-600">
                                    <svg xmlns="http://www.w3.org/2000/svg"
                                         class="h-6 w-6"
                                         fill="none"
                                         viewBox="0 0 24 24"
                                         stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                              d="M8 10h.01M12 10h.01M16 10h.01M9 16h6m2 4H7a2 2 0 01-2-2V6a2 2 0 012-2h2l2-2h2l2 2h2a2 2 0 012 2v12a2 2 0 01-2 2z"/>
                                    </svg>
                                </div>

                                <div>
                                    <div class="text-xs uppercase text-emerald-700 font-semibold tracking-wide">
                                        Комментарий монтажника
                                    </div>
                                    <p class="mt-1 whitespace-pre-line text-emerald-900">
                                        {{ r.actions.find(a => a.action === 'completed')?.note }}
                                    </p>
                                </div>
                            </div>

                            <!-- 📝 Комментарий монтажника при отмене -->
                            <div
                                v-if="
                                    (user.role === 'admin' || user.role === 'engineer')
                                    && r.status === 'cancelled'
                                    && r.actions?.find(a => a.action === 'rejected' && a.note)
                                  "
                                class="mt-4 p-4 rounded-xl border bg-red-50 border-red-200/70 shadow-sm flex items-start gap-3"
                            >
                                <div
                                    class="flex items-center justify-center w-10 h-10 rounded-lg bg-red-100 text-red-600">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none"
                                         viewBox="0 0 24 24"
                                         stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                              d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8V4m0 12v4"/>
                                    </svg>
                                </div>

                                <div>
                                    <div class="text-xs uppercase text-red-700 font-semibold tracking-wide">
                                        Комментарий монтажника при отказе
                                    </div>

                                    <p class="mt-1 whitespace-pre-line text-red-900">
                                        {{
                                            r.actions.find(a => a.action === 'rejected')?.note
                                            ?? '—'
                                        }}
                                    </p>
                                </div>
                            </div>

                        </div>

                        <div v-if="user.role === 'admin' || user.role === 'engineer'" class="mt-4 flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
                            <Link
                                :href="`/requests/${r.id}/edit`"
                                class="w-full sm:w-auto text-center px-4 py-2 text-sm font-semibold text-blue-700 bg-blue-50 rounded-md shadow-sm hover:bg-blue-100 hover:shadow-md transition cursor-pointer"
                            >
                                Редактировать
                            </Link>

                            <button
                                @click="deleteRequest(r.id)"
                                class="px-4 py-2 text-sm font-semibold text-red-700 bg-red-50 rounded-md shadow-sm hover:bg-red-100 hover:shadow-md transition cursor-pointer"
                            >
                                Удалить
                            </button>

                            <button
                                @click="retryRequest(r.id)"
                                class="px-4 py-2 text-sm font-semibold text-white bg-orange-600 rounded-md shadow-sm hover:bg-orange-400 hover:shadow-md transition cursor-pointer"
                            >
                                Отправить в 1С
                            </button>
                        </div>
                    </div>
                    <!-- Пагинация -->
                    <Pagination :total="props.requests.total" :items-per-page="props.requests.per_page"
                                :default-page="props.requests.current_page" v-slot="{ page, setPage }">
                        <PaginationContent v-slot="{ items }">
                            <PaginationPrevious
                                :disabled="!props.requests.prev_page_url"
                                @click="goToPage(props.requests.current_page - 1)"
                            >
                                <span class="sr-only">Previous</span>
                                <svg
                                    class="h-4 w-4"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        stroke-width="2"
                                        d="M15 19l-7-7 7-7"
                                    />
                                </svg>
                            </PaginationPrevious>

                            <template v-for="item in items" :key="item.value">
                                <PaginationItem
                                    v-if="item.type === 'page'"
                                    :value="item.value"
                                    :is-active="item.value === props.requests.current_page"
                                    @click="goToPage(item.value)"
                                >
                                    {{ item.value }}
                                </PaginationItem>

                                <PaginationEllipsis v-else/>
                            </template>

                            <PaginationNext
                                :disabled="!props.requests.next_page_url"
                                @click="goToPage(props.requests.current_page + 1)"
                            >
                                <span class="sr-only">Next</span>
                                <svg
                                    class="h-4 w-4"
                                    fill="none"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        stroke-width="2"
                                        d="M9 5l7 7-7 7"
                                    />
                                </svg>
                            </PaginationNext>
                        </PaginationContent>
                    </Pagination>
                </div>
            </div>
        </div>
    </AppLayout>
</template>

<style scoped>
</style>
