<script setup>
import { ref, computed } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import axios from 'axios'
import CustomerLayout from '@/Layouts/CustomerLayout.vue'
import {
    PhotoIcon,
    ArrowsPointingOutIcon,
    ScissorsIcon,
    ArrowsRightLeftIcon,
    ArrowUturnLeftIcon,
    CodeBracketIcon,
    XMarkIcon,
    InformationCircleIcon,
    FolderIcon,
    DocumentDuplicateIcon,
    CheckIcon,
} from '@heroicons/vue/24/outline'
import { useConfirm } from '@/composables/useConfirm'

const { ask } = useConfirm()

const props = defineProps({
    path: String,
    images: Array,
    error: String,
})

const view = ref('grid') // grid | list
const selected = ref(null)
const showResize = ref(false)
const showThumbnail = ref(false)
const showConvert = ref(false)
const showImgTag = ref(false)
const imgTagOutput = ref('')
const copied = ref(false)

const resizeForm = useForm({ path: '', width: 800, height: null, keep_aspect_ratio: true })
const thumbnailForm = useForm({ path: '', max_size: 200 })
const convertForm = useForm({ path: '', target_format: 'webp', quality: 85 })
const imgTagForm = ref({ path: '', width: 800, height: 600, alt: '' })

const openResize = (img) => {
    selected.value = img
    resizeForm.path = img.path
    resizeForm.width = img.image_width || 800
    resizeForm.height = img.image_height || null
    showResize.value = true
}

const openThumbnail = (img) => {
    selected.value = img
    thumbnailForm.path = img.path
    showThumbnail.value = true
}

const openConvert = (img) => {
    selected.value = img
    convertForm.path = img.path
    showConvert.value = true
}

const openImgTag = async (img) => {
    selected.value = img
    imgTagForm.value = {
        path: img.path,
        width: img.image_width || 800,
        height: img.image_height || 600,
        alt: img.name.replace(/\.[^.]+$/, ''),
    }
    showImgTag.value = true
    await refreshImgTag()
}

const refreshImgTag = async () => {
    try {
        const { data } = await axios.post(route('customer.images.img-tag'), imgTagForm.value)
        imgTagOutput.value = data.tag
    } catch (e) {}
}

const submitResize = () => resizeForm.post(route('customer.images.resize'), {
    preserveScroll: true,
    onSuccess: () => { showResize.value = false },
})
const submitThumbnail = () => thumbnailForm.post(route('customer.images.thumbnail'), {
    preserveScroll: true,
    onSuccess: () => { showThumbnail.value = false },
})
const submitConvert = () => convertForm.post(route('customer.images.convert'), {
    preserveScroll: true,
    onSuccess: () => { showConvert.value = false },
})

const rotate = async (img, degrees) => {
    const ok = await ask({
        title: 'Onaylayın',
        message: `${img.name} ${degrees}° döndürülecek (orijinal değişecek). Devam?`,
        variant: 'warning',
        confirmText: 'Onayla',
        cancelText: 'İptal',
    })
    if (!ok) return
    router.post(route('customer.images.rotate'), { path: img.path, degrees }, { preserveScroll: true })
}

const copyTag = () => {
    navigator.clipboard.writeText(imgTagOutput.value)
    copied.value = true
    setTimeout(() => copied.value = false, 1500)
}

const goPath = (newPath) => {
    router.get(route('customer.images.index', { path: newPath }))
}

const formatSize = (b) => {
    if (b < 1024) return b + ' B'
    if (b < 1024 ** 2) return (b / 1024).toFixed(1) + ' KB'
    return (b / 1024 / 1024).toFixed(1) + ' MB'
}

const breadcrumbs = computed(() => {
    if (!props.path) return []
    const parts = props.path.split('/').filter(Boolean)
    return parts.map((p, i) => ({
        label: p,
        path: parts.slice(0, i + 1).join('/'),
    }))
})
</script>

<template>
    <Head title="Image Manager" />
    <CustomerLayout>
        <template #header>Image Manager (Görüntü Yöneticisi)</template>

        <div class="mb-4 rounded-xl border border-indigo-200 bg-indigo-50 p-4 text-sm text-indigo-900">
            <div class="flex gap-3">
                <InformationCircleIcon class="h-5 w-5 flex-shrink-0 text-indigo-600" />
                <div>
                    <strong>Image Manager:</strong> Sunucu üzerindeki görüntüleri yeniden boyutlandır, thumbnail üret,
                    format dönüştür (JPG ↔ PNG ↔ WebP), döndür. GD kütüphanesi kullanır.
                    <strong>Dikkat:</strong> Resize/Rotate orijinal dosyayı değiştirir — önce yedek al.
                </div>
            </div>
        </div>

        <!-- Path breadcrumb -->
        <div class="mb-3 flex items-center gap-2 text-sm">
            <button @click="goPath('')" class="text-indigo-600 hover:underline">📁 Kök</button>
            <template v-for="(b, i) in breadcrumbs" :key="i">
                <span class="text-slate-400">/</span>
                <button @click="goPath(b.path)" class="text-indigo-600 hover:underline">{{ b.label }}</button>
            </template>
        </div>

        <div v-if="error" class="mb-4 rounded-lg bg-red-50 p-3 text-sm text-red-900">{{ error }}</div>

        <div v-if="images.length === 0" class="rounded-xl border border-dashed border-slate-300 bg-white p-12 text-center">
            <PhotoIcon class="mx-auto h-14 w-14 text-slate-300" />
            <h3 class="mt-3 text-lg font-semibold">Bu klasörde görüntü yok</h3>
            <p class="mt-1 text-sm text-slate-500">JPG, PNG, GIF, WebP, BMP destekleniyor.</p>
            <Link :href="route('customer.files.index')" class="mt-3 inline-flex items-center gap-1 text-sm text-indigo-600 hover:underline">
                <FolderIcon class="h-4 w-4" /> Dosya Yöneticisinden başka klasöre git
            </Link>
        </div>

        <!-- Image grid -->
        <div v-else>
            <div class="mb-3 flex items-center justify-between">
                <p class="text-sm text-slate-600">{{ images.length }} görüntü</p>
                <div class="flex gap-1 text-xs">
                    <button @click="view = 'grid'" :class="['rounded px-3 py-1', view === 'grid' ? 'bg-indigo-600 text-white' : 'bg-slate-100']">Grid</button>
                    <button @click="view = 'list'" :class="['rounded px-3 py-1', view === 'list' ? 'bg-indigo-600 text-white' : 'bg-slate-100']">Liste</button>
                </div>
            </div>

            <!-- Grid view -->
            <div v-if="view === 'grid'" class="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
                <div v-for="img in images" :key="img.path" class="group rounded-xl border border-slate-200 bg-white overflow-hidden shadow-sm hover:shadow-md transition">
                    <div class="aspect-square bg-slate-100 flex items-center justify-center overflow-hidden">
                        <PhotoIcon class="h-16 w-16 text-slate-300" />
                    </div>
                    <div class="p-3">
                        <div class="font-mono text-xs font-semibold truncate" :title="img.name">{{ img.name }}</div>
                        <div class="text-[10px] text-slate-500 mt-0.5">
                            <span v-if="img.image_width">{{ img.image_width }}×{{ img.image_height }}</span>
                            <span class="mx-1">·</span>
                            {{ formatSize(img.size) }}
                            <span class="mx-1">·</span>
                            <span class="font-medium uppercase">{{ img.name.split('.').pop() }}</span>
                        </div>
                        <div class="mt-2 grid grid-cols-2 gap-1">
                            <button @click="openResize(img)" class="rounded border border-blue-300 bg-blue-50 px-2 py-1 text-[10px] text-blue-700 hover:bg-blue-100">
                                <ArrowsPointingOutIcon class="h-3 w-3 inline" /> Boyut
                            </button>
                            <button @click="openThumbnail(img)" class="rounded border border-emerald-300 bg-emerald-50 px-2 py-1 text-[10px] text-emerald-700 hover:bg-emerald-100">
                                <ScissorsIcon class="h-3 w-3 inline" /> Thumb
                            </button>
                            <button @click="openConvert(img)" class="rounded border border-purple-300 bg-purple-50 px-2 py-1 text-[10px] text-purple-700 hover:bg-purple-100">
                                <ArrowsRightLeftIcon class="h-3 w-3 inline" /> Format
                            </button>
                            <button @click="openImgTag(img)" class="rounded border border-amber-300 bg-amber-50 px-2 py-1 text-[10px] text-amber-700 hover:bg-amber-100">
                                <CodeBracketIcon class="h-3 w-3 inline" /> HTML
                            </button>
                        </div>
                        <div class="mt-1 flex gap-1">
                            <button @click="rotate(img, 90)" class="flex-1 rounded border border-slate-300 bg-white px-2 py-1 text-[10px] text-slate-700 hover:bg-slate-50">
                                <ArrowUturnLeftIcon class="h-3 w-3 inline -scale-x-100" /> 90°
                            </button>
                            <button @click="rotate(img, 180)" class="flex-1 rounded border border-slate-300 bg-white px-2 py-1 text-[10px] text-slate-700 hover:bg-slate-50">
                                <ArrowUturnLeftIcon class="h-3 w-3 inline rotate-180" /> 180°
                            </button>
                            <button @click="rotate(img, 270)" class="flex-1 rounded border border-slate-300 bg-white px-2 py-1 text-[10px] text-slate-700 hover:bg-slate-50">
                                <ArrowUturnLeftIcon class="h-3 w-3 inline" /> 270°
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- List view -->
            <div v-else class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
                <table class="min-w-full divide-y divide-slate-200 text-sm">
                    <thead class="bg-slate-50 text-xs uppercase text-slate-500">
                        <tr>
                            <th class="px-3 py-2 text-left">Dosya</th>
                            <th class="px-3 py-2 text-left">Boyut</th>
                            <th class="px-3 py-2 text-left">Dosya Boyutu</th>
                            <th class="px-3 py-2 text-left">Format</th>
                            <th class="px-3 py-2"></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <tr v-for="img in images" :key="img.path" class="hover:bg-slate-50">
                            <td class="px-3 py-2 flex items-center gap-2">
                                <PhotoIcon class="h-5 w-5 text-slate-400" />
                                <span class="font-mono text-xs">{{ img.name }}</span>
                            </td>
                            <td class="px-3 py-2 font-mono text-xs">{{ img.image_width || '?' }}×{{ img.image_height || '?' }}</td>
                            <td class="px-3 py-2 text-xs">{{ formatSize(img.size) }}</td>
                            <td class="px-3 py-2 text-xs uppercase">{{ img.name.split('.').pop() }}</td>
                            <td class="px-3 py-2 text-right">
                                <button @click="openResize(img)" class="rounded p-1 text-blue-600 hover:bg-blue-50"><ArrowsPointingOutIcon class="h-4 w-4" /></button>
                                <button @click="openThumbnail(img)" class="rounded p-1 text-emerald-600 hover:bg-emerald-50"><ScissorsIcon class="h-4 w-4" /></button>
                                <button @click="openConvert(img)" class="rounded p-1 text-purple-600 hover:bg-purple-50"><ArrowsRightLeftIcon class="h-4 w-4" /></button>
                                <button @click="openImgTag(img)" class="rounded p-1 text-amber-600 hover:bg-amber-50"><CodeBracketIcon class="h-4 w-4" /></button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Resize modal -->
        <div v-if="showResize" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Yeniden Boyutlandır</h3>
                    <button @click="showResize = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submitResize" class="space-y-4">
                    <div class="rounded-lg bg-slate-50 p-3 text-sm">
                        <code class="font-mono text-xs">{{ selected?.name }}</code>
                        <div class="text-xs text-slate-500 mt-1">Mevcut: {{ selected?.image_width }}×{{ selected?.image_height }}</div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium">Genişlik (px)</label>
                            <input v-model.number="resizeForm.width" type="number" min="10" max="10000" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Yükseklik (px)</label>
                            <input v-model.number="resizeForm.height" type="number" min="10" max="10000" :disabled="resizeForm.keep_aspect_ratio" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm disabled:bg-slate-100" />
                        </div>
                    </div>
                    <label class="flex items-center gap-2 cursor-pointer text-sm">
                        <input v-model="resizeForm.keep_aspect_ratio" type="checkbox" />
                        <span>En-boy oranını koru</span>
                    </label>
                    <div class="rounded-lg bg-amber-50 p-3 text-xs text-amber-800">
                        ⚠️ Bu işlem orijinal dosyayı değiştirir.
                    </div>
                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button type="button" @click="showResize = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="resizeForm.processing" class="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">Boyutlandır</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Thumbnail modal -->
        <div v-if="showThumbnail" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Thumbnail Oluştur</h3>
                    <button @click="showThumbnail = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submitThumbnail" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium">Maks. Boyut (px)</label>
                        <select v-model.number="thumbnailForm.max_size" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option :value="64">64 (avatar)</option>
                            <option :value="100">100 (küçük)</option>
                            <option :value="200">200 (önerilen)</option>
                            <option :value="300">300 (orta)</option>
                            <option :value="500">500 (büyük thumbnail)</option>
                        </select>
                        <p class="mt-1 text-xs text-slate-500">Orijinal korunur, <code>_thumb{N}.ext</code> uzantılı yeni dosya oluşur.</p>
                    </div>
                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button type="button" @click="showThumbnail = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="thumbnailForm.processing" class="rounded-lg bg-emerald-600 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-700">Oluştur</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Convert modal -->
        <div v-if="showConvert" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">Format Dönüştür</h3>
                    <button @click="showConvert = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <form @submit.prevent="submitConvert" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium">Hedef Format</label>
                        <select v-model="convertForm.target_format" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm">
                            <option value="webp">WebP (modern, küçük boyut)</option>
                            <option value="jpg">JPG (geniş uyumlu)</option>
                            <option value="png">PNG (kayıpsız + transparan)</option>
                            <option value="gif">GIF (animasyonsuz)</option>
                        </select>
                    </div>
                    <div v-if="['jpg', 'jpeg', 'webp'].includes(convertForm.target_format)">
                        <label class="block text-sm font-medium">Kalite ({{ convertForm.quality }})</label>
                        <input v-model.number="convertForm.quality" type="range" min="1" max="100" class="mt-1 w-full" />
                    </div>
                    <div class="rounded-lg bg-blue-50 p-3 text-xs text-blue-900">
                        💡 Yeni format orijinal dosya yanına eklenir, eski dosya silinmez.
                    </div>
                    <div class="flex justify-end gap-2 border-t pt-3">
                        <button type="button" @click="showConvert = false" class="rounded-lg border border-slate-300 px-4 py-2 text-sm">İptal</button>
                        <button type="submit" :disabled="convertForm.processing" class="rounded-lg bg-purple-600 px-4 py-2 text-sm font-medium text-white hover:bg-purple-700">Dönüştür</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- HTML Img Tag modal -->
        <div v-if="showImgTag" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4">
            <div class="w-full max-w-lg rounded-xl bg-white p-6 shadow-xl">
                <div class="mb-4 flex items-center justify-between">
                    <h3 class="text-lg font-semibold">HTML Etiketi Üret</h3>
                    <button @click="showImgTag = false"><XMarkIcon class="h-5 w-5 text-slate-400" /></button>
                </div>
                <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm font-medium">Genişlik</label>
                            <input v-model.number="imgTagForm.width" type="number" @input="refreshImgTag" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium">Yükseklik</label>
                            <input v-model.number="imgTagForm.height" type="number" @input="refreshImgTag" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 font-mono text-sm" />
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium">Alt Text</label>
                        <input v-model="imgTagForm.alt" type="text" @input="refreshImgTag" class="mt-1 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" />
                    </div>

                    <div class="rounded-lg bg-slate-900 p-3">
                        <pre class="font-mono text-xs text-emerald-300 overflow-x-auto"><code>{{ imgTagOutput }}</code></pre>
                    </div>

                    <button @click="copyTag" class="w-full rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                        <DocumentDuplicateIcon class="inline h-4 w-4 mr-1" />
                        {{ copied ? 'Kopyalandı!' : 'HTML\'i Kopyala' }}
                    </button>
                </div>
            </div>
        </div>
    </CustomerLayout>
</template>
