<script setup lang="ts">
/*
import AppLayout from "@/layouts/AppLayout.vue";
import type { BreadcrumbItem } from "@/types";
import { ref } from 'vue'
import { useForm, Head, Link } from '@inertiajs/vue3'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select'
import { toast } from 'vue-sonner'
import { Toaster } from '@/components/ui/sonner'
import axios from 'axios'

interface Installer {
    id: number
    name: string
}

const props = defineProps<{
    installRequest: {
        id: number
        title: string
        description: string | null
        region: string | null
        subject: string | null
        client_name: string | null
        client_phone: string | null
        address: string
        assigned_to: number | null
        scheduled_date: string
        photos?: { id: number; path: string }[]
    }
    installers: Installer[]
}>()

const form = useForm({
    title: props.installRequest.title,
    description: props.installRequest.description || '',
    region: props.installRequest.region || '',
    subject: props.installRequest.subject || '',
    address: props.installRequest.address,
    client_name: props.installRequest.client_name,
    client_phone: props.installRequest.client_phone,
    installer_id: props.installRequest.assigned_to || null,
    scheduled_date: props.installRequest.scheduled_date,
    photos: [] as File[],
    _method: 'PUT',
})

const isImage = (path: string) => /\.(jpg|jpeg|png|gif|webp)$/i.test(path);
const isVideo = (path: string) => /\.(mp4|webm|mov|avi)$/i.test(path);
    /*
const previewUrls = ref<string[]>(
    props.installRequest.photos?.map(p => `/storage/${p.path}`) || []
)*/
/*
const existingMedia = ref(
    props.installRequest.photos || []
)*/
/*
const photos = ref<FileList | null>(null)
const previewUrls = ref<string[]>([])*/
/*
function handleFileChange(event: Event) {
    const files = (event.target as HTMLInputElement).files
    if (files && files.length) {
        form.photos = Array.from(files)
        previewUrls.value = Array.from(files).map(file => URL.createObjectURL(file))
    }
}*/
/*
function handleFileChange(event: Event) {
    const files = (event.target as HTMLInputElement).files

    if (files && files.length) {
        photos.value = files
        form.photos = Array.from(files)

        previewUrls.value = []
        Array.from(files).forEach(file => {
            previewUrls.value.push(URL.createObjectURL(file))
        })
    }
}

function submit() {
    form.post(`/requests/${props.installRequest.id}`, {
        forceFormData: true,
        onSuccess: () => toast.success('Заявка обновлена успешно'),
        onError: () => toast.error('Ошибка при обновлении заявки'),
    })
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Заявки', href: '/requests' },
    { title: `Редактировать #${props.installRequest.id}`, href: `/requests/${props.installRequest.id}/edit` },
]*/
import AppLayout from "@/layouts/AppLayout.vue";
import type { BreadcrumbItem } from "@/types";
import { ref } from 'vue'
import { useForm, Head, Link } from '@inertiajs/vue3'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select'
import { toast } from 'vue-sonner'
import { Toaster } from '@/components/ui/sonner'
import axios from 'axios' // Для удаления на сервере

interface Installer {
    id: number
    name: string
}

const props = defineProps<{
    installRequest: {
        id: number
        title: string
        description: string | null
        region: string | null
        subject: string | null
        client_name: string | null
        client_phone: string | null
        address: string
        assigned_to: number | null
        scheduled_date: string
        photos?: { id: number; path: string }[]
    }
    installers: Installer[]
}>()

const form = useForm({
    title: props.installRequest.title,
    description: props.installRequest.description || '',
    region: props.installRequest.region || '',
    subject: props.installRequest.subject || '',
    address: props.installRequest.address,
    client_name: props.installRequest.client_name,
    client_phone: props.installRequest.client_phone,
    installer_id: props.installRequest.assigned_to || null,
    scheduled_date: props.installRequest.scheduled_date,
    photos: [] as File[],
    _method: 'PUT',
})

const existingMedia = ref(props.installRequest.photos || [])
const photos = ref<FileList | null>(null)
const previewUrls = ref<string[]>([])

function handleFileChange(event: Event) {
    const files = (event.target as HTMLInputElement).files
    if (files && files.length) {
        photos.value = files
        form.photos = Array.from(files)

        previewUrls.value = []
        Array.from(files).forEach(file => {
            previewUrls.value.push(URL.createObjectURL(file))
        })
    }
}

// Проверка типа файла
function isImage(path: string | File) {
    const name = typeof path === 'string' ? path : path.name
    return /\.(jpg|jpeg|png|gif|webp)$/i.test(name)
}

function isVideo(path: string | File) {
    const name = typeof path === 'string' ? path : path.name
    return /\.(mp4|webm|mov|avi)$/i.test(name)
}

// Удаление старого медиа сразу на сервере
async function removeExistingMedia(id: number) {
    try {
        await axios.delete(`/media/${id}`) // Эндпоинт удаления на сервере
        existingMedia.value = existingMedia.value.filter(m => m.id !== id)
        toast.success('Медиа удалено')
    } catch (error) {
        console.error(error)
        toast.error('Не удалось удалить медиа')
    }
}

// Удаление нового медиа из формы
function removeNewMedia(index: number) {
    previewUrls.value.splice(index, 1)
    form.photos.splice(index, 1)
}

function submit() {
    form.post(`/requests/${props.installRequest.id}`, {
        forceFormData: true,
        onSuccess: () => toast.success('Заявка обновлена успешно'),
        onError: () => toast.error('Ошибка при обновлении заявки'),
    })
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Заявки', href: '/requests' },
    { title: `Редактировать #${props.installRequest.id}`, href: `/requests/${props.installRequest.id}/edit` },
]
</script>

<template>
    <Head :title="`Редактировать заявку #${props.installRequest.id}`" />

    <AppLayout :breadcrumbs="breadcrumbs">
        <div class="flex h-full flex-1 flex-col gap-4 rounded-xl p-4">
            <Toaster />
            <h1 class="text-2xl font-bold mb-6">Редактировать заявку #{{ props.installRequest.id }}</h1>

            <form @submit.prevent="submit" class="space-y-6 max-w-xl">
                <!-- Заголовок -->
                <div class="space-y-2">
                    <Label for="title">Заголовок</Label>
                    <Input id="title" v-model="form.title" placeholder="Введите заголовок" />
                    <p v-if="form.errors.title" class="text-sm text-red-500">{{ form.errors.title }}</p>
                </div>

                <!-- Описание -->
                <div class="space-y-2">
                    <Label for="description">Описание</Label>
                    <textarea
                        id="description"
                        v-model="form.description"
                        rows="4"
                        class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm"
                        placeholder="Краткое описание (необязательно)"
                    ></textarea>
                </div>

                <!-- Регион -->
                <div class="space-y-2">
                    <Label for="region">Регион</Label>
                    <Input id="region" v-model="form.region" placeholder="Укажите регион" />
                    <p v-if="form.errors.region" class="text-sm text-red-500">{{ form.errors.region }}</p>
                </div>

                <!-- Субъект -->
                <div class="space-y-2">
                    <Label for="subject">Субъект</Label>
                    <Select v-model="form.subject" class="w-full">
                        <SelectTrigger class="w-full">
                            <SelectValue placeholder="-- Не назначен --" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectLabel>Субъект</SelectLabel>
                                <SelectItem :value="null">-- Не назначен --</SelectItem>
                                <SelectItem value="Физическое лицо">Физическое лицо</SelectItem>
                                <SelectItem value="Юридическое лицо">Юридическое лицо</SelectItem>
                            </SelectGroup>
                        </SelectContent>
                    </Select>
                    <p v-if="form.errors.subject" class="text-sm text-red-500">{{ form.errors.subject }}</p>
                </div>

                <div class="space-y-2">
                    <Label for="region">Клиент</Label>
                    <Input id="region" v-model="form.client_name" placeholder="Укажите имя" />
                    <p class="text-sm text-red-500" v-if="form.errors.client_name">{{ form.errors.client_name }}</p>
                </div>

                <div class="space-y-2">
                    <Label for="region">Телефон</Label>
                    <Input id="region" v-model="form.client_phone" placeholder="Укажите контактный телефон" />
                    <p class="text-sm text-red-500" v-if="form.errors.client_phone">{{ form.errors.client_phone }}</p>
                </div>

                <!-- Адрес -->
                <div class="space-y-2">
                    <Label for="address">Адрес</Label>
                    <Input id="address" v-model="form.address" placeholder="Адрес установки" />
                    <p v-if="form.errors.address" class="text-sm text-red-500">{{ form.errors.address }}</p>
                </div>

                <!-- Монтажник -->
                <div class="space-y-2">
                    <Label for="installer_id">Назначить монтажника</Label>
                    <Select v-model="form.installer_id" class="w-full">
                        <SelectTrigger class="w-full">
                            <SelectValue placeholder="-- Не назначен --" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectLabel>Монтажники</SelectLabel>
                                <SelectItem :value="null">-- Не назначен --</SelectItem>
                                <SelectItem
                                    v-for="installer in props.installers"
                                    :key="installer.id"
                                    :value="installer.id"
                                >
                                    {{ installer.name }}
                                </SelectItem>
                            </SelectGroup>
                        </SelectContent>
                    </Select>
                    <p v-if="form.errors.installer_id" class="text-sm text-red-500">{{ form.errors.installer_id }}</p>
                </div>

                <!-- Дата и время -->
                <div class="space-y-2">
                    <Label for="scheduled_date">Дата и время</Label>
                    <Input id="scheduled_date" v-model="form.scheduled_date" type="datetime-local" />
                    <p v-if="form.errors.scheduled_date" class="text-sm text-red-500">{{ form.errors.scheduled_date }}</p>
                </div>

                <!-- Фото -->
                <div class="space-y-2">
                    <div class="grid w-full max-w-sm items-center gap-1.5">
                        <Label for="photos">Фото заявки (до 20Мб)</Label>
                        <Input id="photos" type="file" multiple accept="image/*,video/*" @change="handleFileChange" />
                    </div>
                    <p v-if="form.errors.photos" class="text-sm text-red-500">{{ form.errors.photos }}</p>
                </div>

                <!-- Предпросмотр фото -->
                <!--
                <div class="flex gap-4 flex-wrap mt-2">

                    <div v-for="media in existingMedia" :key="'old-' + media.id">

                        <template v-if="isImage(media.path)">
                            <img :src="`/storage/${media.path}`" class="w-32 h-32 object-cover rounded border" />
                        </template>

                        <template v-else-if="isVideo(media.path)">
                            <video
                                :src="`/storage/${media.path}`"
                                class="w-32 h-32 object-cover rounded border"
                                controls
                                preload="metadata"
                                muted
                            />
                        </template>

                    </div>

                </div>
                -->
                <div class="flex gap-4 flex-wrap mt-2">
                    <!-- Старые медиа -->
                    <div v-for="media in existingMedia" :key="'old-' + media.id" class="relative">
                        <template v-if="isImage(media.path)">
                            <img :src="`/storage/${media.path}`" class="w-32 h-32 object-cover rounded border" />
                        </template>
                        <template v-else-if="isVideo(media.path)">
                            <video :src="`/storage/${media.path}`" class="w-32 h-32 object-cover rounded border" controls muted preload="metadata"/>
                        </template>
                        <button @click="removeExistingMedia(media.id)"
                                class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-600"
                                type="button">×
                        </button>
                    </div>

                    <!-- Новые медиа -->
                    <div v-for="(url, index) in previewUrls" :key="'new-' + index" class="relative">
                        <template v-if="photos && photos[index]?.type.startsWith('image/')">
                            <img :src="url" class="w-32 h-32 object-cover rounded border" />
                        </template>
                        <template v-else>
                            <video :src="url" class="w-32 h-32 object-cover rounded border" controls muted preload="metadata"/>
                        </template>
                        <button @click="removeNewMedia(index)"
                                class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-600"
                                type="button">×
                        </button>
                    </div>
                </div>


                <!-- Кнопки -->
                <div class="flex justify-between items-center pt-4">
                    <Link href="/requests" class="text-sm text-gray-600 underline hover:text-gray-800">
                        Назад к списку
                    </Link>
                    <Button type="submit" :disabled="form.processing">
                        {{ form.processing ? 'Сохранение...' : 'Сохранить изменения' }}
                    </Button>
                </div>
            </form>
        </div>
    </AppLayout>
</template>

<style scoped>

</style>
