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

import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover'

import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList,
} from '@/components/ui/command'

import { Check, ChevronsUpDown, Upload } from 'lucide-vue-next'

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Панель управления', href: '/dashboard' },
    { title: 'Заявки', href: '/requests' },
    { title: 'Добавление заявки', href: '#' },
];

const form = useForm({
    title: '',
    description: '',
    address: '',
    scheduled_date: '',
    region: '',
    client_name: '',
    client_phone: '',
    subject: '',
    installer_id: null as number | null,
});

const fileInput = ref<HTMLInputElement | null>(null)

// ❗ FIX: массив вместо FileList
const photos = ref<File[]>([]);
const previewUrls = ref<string[]>([]);

const openCity = ref(false);
const citySearch = ref('');

const cityTrigger = ref<HTMLElement | null>(null);
const triggerWidth = ref(0);

const props = defineProps<{
    installers: { id: number; name: string }[];
    cities: { id: number; name: string }[];
}>();

const filteredCities = computed(() => {
    if (!citySearch.value) return props.cities;
    const q = citySearch.value.toLowerCase();
    return props.cities.filter(city => city.name.toLowerCase().includes(q));
});

const updateTriggerWidth = () => {
    if (cityTrigger.value) triggerWidth.value = cityTrigger.value.offsetWidth;
};

watch(openCity, (isOpen) => {
    if (isOpen) nextTick(updateTriggerWidth);
});

onMounted(() => nextTick(updateTriggerWidth));

const handleFileChange = (e: Event) => {
    const target = e.target as HTMLInputElement;

    if (target?.files) {
        const files = Array.from(target.files);

        photos.value = [...photos.value, ...files];

        files.forEach(file => {
            previewUrls.value.push(URL.createObjectURL(file));
        });
    }
};

// ✅ удаление файла
const removePhoto = (index: number) => {
    photos.value.splice(index, 1);

    URL.revokeObjectURL(previewUrls.value[index]);
    previewUrls.value.splice(index, 1);

    // если файлов не осталось — чистим input
    if (!photos.value.length && fileInput.value) {
        fileInput.value.value = '';
    }
};

const submit = () => {
    const payload = new FormData()
    const data = form.data()

    Object.entries(data).forEach(([key, value]) => {
        payload.append(key, value?.toString() ?? '')
    })

    if (photos.value.length) {
        photos.value.forEach(file => {
            payload.append('photos[]', file)
        })
    }

    router.post('/requests', payload, {
        forceFormData: true,
        preserveScroll: true,
        onSuccess: () => {
            toast.success('Заявка создана: Фото и данные успешно отправлены')
            form.reset()
            photos.value = []
            previewUrls.value = []

            if (fileInput.value) fileInput.value.value = ''
        },
        onError: (errors) => {
            form.errors = errors
            toast.error('Ошибка при создании заявки')
        },
    })
}
</script>

<template>
    <Head title="Заявки на монтаж" />
    <AppLayout :breadcrumbs="breadcrumbs">
        <div class="flex h-full flex-1 flex-col gap-4 rounded-xl p-6">
            <h1 class="text-3xl font-bold mb-6">Новая заявка</h1>

            <form @submit.prevent="submit" class="space-y-10 max-w-2xl">

                <!-- Основная информация -->
                <div class="space-y-6">
                    <div class="border-b pb-3">
                        <h2 class="text-lg font-semibold flex items-center gap-2">
                            <span class="text-primary">●</span>
                            Основная информация
                        </h2>
                    </div>

                    <div class="space-y-2">
                        <Label for="title">Заголовок</Label>
                        <Input id="title" v-model="form.title" placeholder="Введите заголовок"  :class="form.errors.title ? '!border-red-500 !focus-visible:border-red-500' : ''" class="h-11" />
                    </div>

                    <div class="space-y-2">
                        <Label for="description">Описание</Label>
                        <Textarea id="description" v-model="form.description" rows="4" placeholder="Краткое описание (необязательно)" />
                    </div>
                </div>

                <!-- Локация -->
                <div class="space-y-6">
                    <div class="border-b pb-3">
                        <h2 class="text-lg font-semibold flex items-center gap-2">
                            <span class="text-primary">●</span>
                            Локация
                        </h2>
                    </div>

                    <div class="space-y-2">
                        <Label>Город / Регион</Label>
                        <Popover v-model:open="openCity">
                            <PopoverTrigger as-child>
                                <Button ref="cityTrigger" variant="outline" class="w-full justify-between h-11" :class="form.errors.title ? '!border-red-500 !focus-visible:border-red-500' : ''">
                                    {{ form.region || 'Выберите город...' }}
                                    <ChevronsUpDown class="ml-2 h-4 w-4 opacity-50" />
                                </Button>
                            </PopoverTrigger>
                            <PopoverContent class="p-0" align="start" :style="{ width: triggerWidth + 'px' }">
                                <Command>
                                    <CommandInput v-model="citySearch" placeholder="Поиск города..." />
                                    <CommandList>
                                        <CommandEmpty>Город не найден</CommandEmpty>
                                        <CommandGroup>
                                            <CommandItem
                                                v-for="city in filteredCities"
                                                :key="city.id"
                                                @select="() => { form.region = city.name; openCity = false; citySearch = '' }"
                                            >
                                                <Check v-if="form.region === city.name" class="mr-2 h-4 w-4" />
                                                {{ city.name }}
                                            </CommandItem>
                                        </CommandGroup>
                                    </CommandList>
                                </Command>
                            </PopoverContent>
                        </Popover>
                    </div>

                    <div class="space-y-2">
                        <Label for="address">Адрес установки</Label>
                        <Input id="address" v-model="form.address" :class="form.errors.title ? '!border-red-500 !focus-visible:border-red-500' : ''" placeholder="Адрес установки" class="h-11" />
                    </div>
                </div>

                <!-- Клиент -->
                <div class="space-y-6">
                    <div class="border-b pb-3">
                        <h2 class="text-lg font-semibold flex items-center gap-2">
                            <span class="text-primary">●</span>
                            Информация о клиенте
                        </h2>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-2">
                            <Label>Клиент</Label>
                            <Input v-model="form.client_name" placeholder="Укажите имя" class="h-11" />
                            <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>Телефон</Label>
                            <Input v-model="form.client_phone" placeholder="Укажите контактный телефон" class="h-11" />
                            <p class="text-sm text-red-500" v-if="form.errors.client_phone">{{ form.errors.client_phone }}</p>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <Label>Субъект</Label>
                        <Select v-model="form.subject">
                            <SelectTrigger class="w-full" size="lg">
                                <SelectValue placeholder="-- Не назначен --" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectGroup>
                                    <SelectLabel>Субъект</SelectLabel>
                                    <SelectItem value="Физическое лицо">Физическое лицо</SelectItem>
                                    <SelectItem value="Юридическое лицо">Юридическое лицо</SelectItem>
                                </SelectGroup>
                            </SelectContent>
                        </Select>
                    </div>
                </div>

                <!-- Монтаж и сроки -->
                <div class="space-y-6">
                    <div class="border-b pb-3">
                        <h2 class="text-lg font-semibold flex items-center gap-2">
                            <span class="text-primary">●</span>
                            Монтаж и сроки
                        </h2>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-2">
                            <Label>Назначить монтажника</Label>
                            <Select v-model="form.installer_id">
                                <SelectTrigger class="w-full" size="lg">
                                    <SelectValue placeholder="-- Не назначен --" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectGroup>
                                        <SelectLabel>Монтажники</SelectLabel>
                                        <SelectItem value="null">-- Не назначен --</SelectItem>
                                        <SelectItem v-for="installer in installers" :key="installer.id" :value="installer.id">
                                            {{ installer.name }}
                                        </SelectItem>
                                    </SelectGroup>
                                </SelectContent>
                            </Select>
                            <p class="text-sm text-red-500" v-if="form.errors.installer_id">{{ 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" :class="form.errors.title ? '!border-red-500 !focus-visible:border-red-500' : ''" type="datetime-local" class="h-11" />
                        </div>
                    </div>
                </div>

                <div class="space-y-6">
                    <div class="border-b pb-3">
                        <h2 class="text-lg font-semibold flex items-center gap-2">
                            <span class="text-primary">●</span>
                            Фото заявки
                        </h2>
                    </div>

                    <div class="space-y-2">
                        <Label>Прикрепите фото или видео</Label>

                        <div
                            class="border-2 border-dashed border-muted-foreground/30 hover:border-primary/50 rounded-2xl p-8 transition-colors cursor-pointer bg-muted/30 hover:bg-muted/50"
                            :class="{
                                'border-red-500': form.errors.photos,
                                'border-muted-foreground/30 hover:border-primary/50': !form.errors.photos
                            }"
                            @click="fileInput?.click()"
                        >
                            <div class="flex flex-col items-center text-center">
                                <Upload class="w-10 h-10 mb-3" />
                                <p class="font-medium">Нажмите для загрузки</p>
                                <p class="text-sm text-muted-foreground">или перетащите файлы сюда</p>
                                <p class="text-xs text-muted-foreground mt-2">JPG, PNG, MP4 (до 20 МБ)</p>
                            </div>
                        </div>

                        <input
                            ref="fileInput"
                            type="file"
                            multiple
                            accept="image/*,video/*"
                            @change="handleFileChange"
                            class="hidden"
                        />

                        <p class="text-sm text-red-500" v-if="form.errors.photos">
                            {{ form.errors.photos }}
                        </p>
                    </div>

                    <!-- ✅ превью + удаление -->
                    <div v-if="previewUrls.length" class="flex gap-4 flex-wrap">
                        <div
                            v-for="(url, index) in previewUrls"
                            :key="index"
                            class="relative group"
                        >
                            <img :src="url" class="w-32 h-32 object-cover rounded-xl border" />

                            <button
                                type="button"
                                @click="removePhoto(index)"
                                class="absolute top-1 right-1 bg-black/60 text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition"
                            >
                                ✕
                            </button>
                        </div>
                    </div>
                </div>

                <Button type="submit" :disabled="form.processing" size="lg" class="w-full h-12 cursor-pointer">
                    {{ form.processing ? 'Создание...' : 'Создать заявку' }}
                </Button>
            </form>
        </div>
    </AppLayout>
</template>

<style scoped>

</style>
