<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import Dialog from 'primevue/dialog'
import Button from 'primevue/button'
import Tag from 'primevue/tag'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    previewImages: {
        type: Array,
        default: () => []
    },
    initialIndex: {
        type: Number,
        default: 0
    },
    apiUrl: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['update:visible', 'reusePrompt', 'reuseAsset', 'useResultAsAsset'])

const previewIndex = ref(0)
const previewImage = computed(() => props.previewImages[previewIndex.value] || null)

// Reset index when modal opens
watch(() => props.visible, (newVal) => {
    if (newVal) {
        previewIndex.value = props.initialIndex
        window.addEventListener('keydown', handlePreviewKeydown)
    } else {
        window.removeEventListener('keydown', handlePreviewKeydown)
    }
})

const close = () => {
    emit('update:visible', false)
}

const navigatePreview = (direction) => {
    const count = props.previewImages.length
    if (count <= 1) return
    let newIndex = previewIndex.value + direction
    if (newIndex < 0) newIndex = count - 1
    if (newIndex >= count) newIndex = 0
    previewIndex.value = newIndex
}

const handlePreviewKeydown = (e) => {
    if (!props.visible) return
    if (e.key === 'ArrowLeft') { navigatePreview(-1); e.preventDefault() }
    if (e.key === 'ArrowRight') { navigatePreview(1); e.preventDefault() }
    if (e.key === 'Escape') { close(); e.preventDefault() }
}

onBeforeUnmount(() => {
    window.removeEventListener('keydown', handlePreviewKeydown)
})

const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('ru-RU', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    })
}

const copyToClipboard = (text) => {
    if (!text) return
    navigator.clipboard.writeText(text).then(() => {
        // Parent could show a toast if needed, or we just log
        console.log('Copied to clipboard')
    })
}

// Actions
const onReusePrompt = () => {
    if (previewImage.value?.gen) emit('reusePrompt', previewImage.value.gen)
}

const onReuseAsset = () => {
    if (previewImage.value?.gen) emit('reuseAsset', previewImage.value.gen)
}

const onUseResultAsAsset = () => {
    if (previewImage.value?.gen) emit('useResultAsAsset', previewImage.value.gen)
}
</script>

<template>
    <Dialog :visible="visible" @update:visible="val => emit('update:visible', val)" modal dismissableMask
        :style="{ width: '95vw', maxWidth: '1200px' }"
        class="preview-dialog"
        :pt="{ 
            root: { class: '!bg-transparent !border-none !shadow-none' }, 
            header: { class: '!hidden' }, 
            content: { class: '!p-0 !bg-transparent' } 
        }">
        
        <div v-if="previewImage" class="flex flex-col lg:flex-row h-[90vh] w-full overflow-hidden relative bg-slate-900/95 backdrop-blur-xl border border-white/10 shadow-2xl rounded-3xl" @click.stop>
            
            <!-- Left: Image Viewer -->
            <div class="flex-1 bg-black/40 flex items-center justify-center relative min-h-[40vh] lg:min-h-0 border-r border-white/5">
                
                <!-- Navigation Buttons -->
                <Button v-if="previewImages.length > 1" icon="pi pi-chevron-left" @click.stop="navigatePreview(-1)"
                    rounded text
                    class="!absolute left-4 top-1/2 -translate-y-1/2 z-20 !text-white !bg-black/50 hover:!bg-black/70 !w-12 !h-12 !rounded-full !border !border-white/10 backdrop-blur-md transition-all hover:scale-110" />

                <Button v-if="previewImages.length > 1" icon="pi pi-chevron-right" @click.stop="navigatePreview(1)"
                    rounded text
                    class="!absolute right-4 top-1/2 -translate-y-1/2 z-20 !text-white !bg-black/50 hover:!bg-black/70 !w-12 !h-12 !rounded-full !border !border-white/10 backdrop-blur-md transition-all hover:scale-110" />

                <!-- Main Image -->
                <img :src="previewImage.url"
                    class="max-w-full max-h-[85vh] object-contain shadow-2xl transition-transform duration-300"
                    draggable="false" />

                <!-- Image Index Badge -->
                <div v-if="previewImages.length > 1"
                    class="absolute bottom-4 left-1/2 -translate-x-1/2 z-20 bg-black/60 backdrop-blur-md text-white text-xs font-mono px-3 py-1.5 rounded-full border border-white/10">
                    {{ previewIndex + 1 }} / {{ previewImages.length }}
                </div>

                <!-- Close Button (Mobile Only) -->
                <Button icon="pi pi-times" @click="close" rounded text
                    class="absolute top-4 right-4 z-30 lg:hidden !text-white !bg-black/50 !w-10 !h-10" />
            </div>

            <!-- Right: Generation Info & Actions -->
            <div class="w-full lg:w-96 flex flex-col bg-slate-900/50 backdrop-blur-md overflow-hidden">
                
                <!-- Header -->
                <div class="p-5 border-b border-white/10 flex justify-between items-center">
                    <div>
                        <h3 class="text-lg font-bold text-white m-0">Generation Details</h3>
                        <p class="text-[10px] text-slate-500 font-mono uppercase tracking-widest mt-0.5">
                            {{ previewImage?.gen?.id || previewImage?.gen?._id || 'Unknown ID' }}
                        </p>
                    </div>
                    <Button icon="pi pi-times" @click="close" rounded text
                        class="!hidden lg:!flex !text-slate-500 hover:!text-white !w-8 !h-8" />
                </div>

                <!-- Scrollable Content -->
                <div class="flex-1 overflow-y-auto p-5 custom-scrollbar flex flex-col gap-6">
                    
                    <!-- Actions Section -->
                    <div v-if="previewImage?.gen" class="flex flex-col gap-2">
                        <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest px-1">Actions</label>
                        <div class="grid grid-cols-1 gap-2">
                            <Button label="Reuse Prompt" icon="pi pi-refresh" @click="onReusePrompt"
                                class="!bg-violet-600/10 !border-violet-500/30 !text-violet-400 hover:!bg-violet-600/20 !text-sm !justify-start" />
                            
                            <Button label="Reuse References" icon="pi pi-clone" @click="onReuseAsset"
                                class="!bg-blue-600/10 !border-blue-500/30 !text-blue-400 hover:!bg-blue-600/20 !text-sm !justify-start" />
                            
                            <Button label="Reference Result" icon="pi pi-image" @click="onUseResultAsAsset"
                                class="!bg-emerald-600/10 !border-emerald-500/30 !text-emerald-400 hover:!bg-emerald-600/20 !text-sm !justify-start" />
                        </div>
                    </div>

                    <!-- Prompt Section -->
                    <div v-if="previewImage?.gen?.prompt" class="flex flex-col gap-2">
                        <div class="flex justify-between items-center px-1">
                            <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Prompt</label>
                            <Button icon="pi pi-copy" @click="copyToClipboard(previewImage.gen.prompt)" 
                                text class="!p-0 !w-6 !h-6 !text-slate-500 hover:!text-white" v-tooltip.top="'Copy Prompt'" />
                        </div>
                        <div class="bg-black/30 p-3 rounded-xl border border-white/5 text-sm text-slate-300 leading-relaxed max-h-40 overflow-y-auto custom-scrollbar">
                            {{ previewImage.gen.prompt }}
                        </div>
                    </div>

                    <!-- Technical Data -->
                    <div v-if="previewImage?.gen" class="flex flex-col gap-2">
                        <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest px-1">Technical Data</label>
                        <div class="flex flex-col gap-3 bg-black/20 p-4 rounded-xl border border-white/5">
                            <!-- Grid for main params -->
                            <div class="grid grid-cols-2 gap-3">
                                <div class="flex flex-col gap-0.5">
                                    <span class="text-[10px] text-slate-500 uppercase">Quality</span>
                                    <span class="text-xs text-slate-200 font-semibold">{{ previewImage.gen.quality || 'N/A' }}</span>
                                </div>
                                <div class="flex flex-col gap-0.5">
                                    <span class="text-[10px] text-slate-500 uppercase">Aspect Ratio</span>
                                    <span class="text-xs text-slate-200 font-semibold">{{ previewImage.gen.aspect_ratio || 'N/A' }}</span>
                                </div>
                                <div class="flex flex-col gap-0.5">
                                    <span class="text-[10px] text-slate-500 uppercase">Execution Time</span>
                                    <span class="text-xs text-slate-200 font-semibold">{{ previewImage.gen.execution_time_seconds?.toFixed(2) || '0' }}s (API: {{ previewImage.gen.api_execution_time_seconds?.toFixed(2) || '0' }}s)</span>
                                </div>
                                <div class="flex flex-col gap-0.5">
                                    <span class="text-[10px] text-slate-500 uppercase">Cost</span>
                                    <span class="text-xs text-emerald-400 font-bold">${{ previewImage.gen.cost?.toFixed(4) || '0.00' }}</span>
                                </div>
                            </div>

                            <div class="h-px bg-white/5 w-full"></div>

                            <!-- Tokens Section -->
                            <div class="flex flex-col gap-2">
                                <span class="text-[10px] text-slate-500 uppercase">Token Usage</span>
                                <div class="grid grid-cols-3 gap-2">
                                    <div class="flex flex-col bg-white/5 p-2 rounded-lg items-center">
                                        <span class="text-[8px] text-slate-500 uppercase">Input</span>
                                        <span class="text-[10px] text-slate-200 font-mono">{{ previewImage.gen.input_token_usage || 0 }}</span>
                                    </div>
                                    <div class="flex flex-col bg-white/5 p-2 rounded-lg items-center">
                                        <span class="text-[8px] text-slate-500 uppercase">Output</span>
                                        <span class="text-[10px] text-slate-200 font-mono">{{ previewImage.gen.output_token_usage || 0 }}</span>
                                    </div>
                                    <div class="flex flex-col bg-violet-600/20 p-2 rounded-lg items-center border border-violet-500/20">
                                        <span class="text-[8px] text-violet-400 uppercase">Total</span>
                                        <span class="text-[10px] text-violet-300 font-bold font-mono">{{ previewImage.gen.token_usage || 0 }}</span>
                                    </div>
                                </div>
                            </div>

                            <div class="h-px bg-white/5 w-full"></div>

                            <!-- Technical Prompt -->
                            <div v-if="previewImage?.gen?.tech_prompt" class="flex flex-col gap-2">
                                <div class="flex justify-between items-center">
                                    <span class="text-[10px] text-slate-500 uppercase">Technical Prompt</span>
                                    <Button icon="pi pi-copy" @click="copyToClipboard(previewImage.gen.tech_prompt)" 
                                        text class="!p-0 !w-4 !h-4 !text-slate-500 hover:!text-white" />
                                </div>
                                <div class="bg-black/40 p-2 rounded-lg border border-white/5 text-[10px] font-mono text-slate-400 leading-relaxed max-h-24 overflow-y-auto custom-scrollbar whitespace-pre-wrap">
                                    {{ previewImage.gen.tech_prompt }}
                                </div>
                            </div>

                            <div class="h-px bg-white/5 w-full"></div>

                            <!-- Metadata -->
                            <div class="flex flex-col gap-1.5 text-[10px]">
                                <div class="flex justify-between">
                                    <span class="text-slate-500 uppercase">Created:</span>
                                    <span class="text-slate-300">{{ formatDate(previewImage.gen.created_at) }}</span>
                                </div>
                                <div v-if="previewImage.gen.generation_group_id" class="flex justify-between">
                                    <span class="text-slate-500 uppercase">Group ID:</span>
                                    <span class="text-slate-300 font-mono">{{ previewImage.gen.generation_group_id }}</span>
                                </div>
                                <div v-if="previewImage.gen.idea_id" class="flex justify-between">
                                    <span class="text-slate-500 uppercase">Idea ID:</span>
                                    <span class="text-slate-300 font-mono">{{ previewImage.gen.idea_id }}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-slate-500 uppercase">Status:</span>
                                    <Tag :value="previewImage.gen.status" 
                                        :severity="previewImage.gen.status === 'done' ? 'success' : (previewImage.gen.status === 'failed' ? 'danger' : 'info')" 
                                        class="!text-[8px] !px-1.5 !py-0 w-fit h-4" />
                                </div>
                                <div v-if="previewImage.gen.failed_reason" class="flex flex-col gap-1 mt-1 p-2 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400">
                                    <span class="uppercase font-bold">Error:</span>
                                    <span class="italic">{{ previewImage.gen.failed_reason }}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- References Used -->
                    <div v-if="previewImage?.gen?.assets_list?.length > 0" class="flex flex-col gap-2">
                        <label class="text-[10px] font-bold text-slate-500 uppercase tracking-widest px-1">References Used</label>
                        <div class="flex flex-wrap gap-2">
                            <div v-for="assetId in previewImage.gen.assets_list" :key="assetId"
                                class="w-10 h-10 rounded-lg overflow-hidden border border-white/10 shadow-lg">
                                <img :src="apiUrl + '/assets/' + assetId + '?thumbnail=true'" 
                                    class="w-full h-full object-cover" />
                            </div>
                        </div>
                    </div>

                </div>
            </div>

        </div>
    </Dialog>
</template>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
    width: 4px;
}
.custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.2);
}
</style>
