<script setup>
import { computed } from 'vue'
import {
    XMarkIcon, InformationCircleIcon, FolderOpenIcon, DocumentIcon,
    ClipboardDocumentIcon,
} from '@heroicons/vue/24/outline'
import { useFileIcon, formatBytes, formatDate, relativeTime } from '@/Composables/useFileIcons'

/**
 * Read-only "Özellikler" (Properties) modal.
 *
 * Shows whatever metadata the row carries. Fields that the backend didn't
 * populate (e.g. owner/group on listings that skip stat() for speed) render
 * as "—" rather than disappearing — this keeps the layout stable across
 * different rows.
 *
 * Props:
 *   - show       v-model:show
 *   - item       row object (name, path, type, size, permissions, mime,
 *                  modified, owner?, group?, mode_octal?, mode_symbolic?)
 *   - home       absolute home prefix (e.g. /home/onx_user) — used to render
 *                  the full path. Optional.
 */
const props = defineProps({
    show: { type: Boolean, default: false },
    item: { type: Object, default: null },
    home: { type: String, default: '' },
})

const emit = defineEmits(['update:show', 'close'])

const { iconFor } = useFileIcon()

const isDir = computed(() => props.item?.type === 'dir' || props.item?.type === 'folder')

const fullPath = computed(() => {
    if (!props.item) return ''
    if (props.home && props.item.path) return `${props.home}/${props.item.path}`
    if (props.home) return props.home
    return props.item.path || props.item.name || ''
})

const permsDisplay = computed(() => {
    const i = props.item
    if (!i) return '—'
    const octal = i.mode_octal || i.permissions || ''
    const sym = i.mode_symbolic || ''
    if (octal && sym) return `${octal} (${sym})`
    return octal || sym || '—'
})

const ownerDisplay = computed(() => {
    const i = props.item
    if (!i) return '—'
    if (i.owner && i.group) return `${i.owner}:${i.group}`
    if (i.owner) return i.owner
    if (i.uid !== undefined && i.gid !== undefined) return `${i.uid}:${i.gid}`
    return '—'
})

const sizeDisplay = computed(() => {
    if (!props.item) return '—'
    if (isDir.value) return props.item.items_count != null ? `${props.item.items_count} öğe` : '—'
    return formatBytes(props.item.size)
})

const mtimeDisplay = computed(() => {
    const ts = props.item?.modified ?? props.item?.mtime
    if (!ts) return '—'
    return `${formatDate(ts)} (${relativeTime(ts)})`
})

const atimeDisplay = computed(() => {
    const ts = props.item?.atime
    return ts ? formatDate(ts) : '—'
})

const ctimeDisplay = computed(() => {
    const ts = props.item?.ctime
    return ts ? formatDate(ts) : '—'
})

const mimeDisplay = computed(() => {
    if (!props.item) return '—'
    if (isDir.value) return 'directory'
    return props.item.mime || '—'
})

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

const copyFullPath = async () => {
    try {
        await navigator.clipboard?.writeText(fullPath.value)
        window.$toast?.info?.('Yol kopyalandı')
    } catch {
        window.$toast?.error?.('Panoya yazılamadı.')
    }
}

const onKeydown = (e) => {
    if (e.key === 'Escape') close()
}
</script>

<template>
    <Teleport to="body">
        <div v-if="show && item"
             class="fixed inset-0 z-[9999] flex items-center justify-center bg-slate-900/60 p-4 backdrop-blur-sm"
             @click.self="close"
             @keydown="onKeydown"
             tabindex="-1">
            <div class="w-full max-w-md overflow-hidden rounded-2xl bg-white shadow-2xl dark:bg-slate-900">
                <!-- Header -->
                <div class="flex items-center gap-3 border-b border-slate-200 bg-slate-50 px-5 py-3 dark:border-slate-700 dark:bg-slate-800/60">
                    <InformationCircleIcon class="h-5 w-5 text-indigo-500" />
                    <h3 class="flex-1 truncate text-base font-semibold text-slate-900 dark:text-slate-100"
                        :title="item.name">
                        Özellikler — {{ item.name }}
                    </h3>
                    <button type="button"
                            @click="close"
                            class="rounded p-1 text-slate-400 hover:bg-slate-200 hover:text-slate-700 dark:hover:bg-slate-700 dark:hover:text-slate-200">
                        <XMarkIcon class="h-5 w-5" />
                    </button>
                </div>

                <!-- Body -->
                <div class="p-5">
                    <!-- Top tile (icon + name + type) -->
                    <div class="mb-4 flex items-center gap-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 dark:border-slate-700 dark:bg-slate-800/60">
                        <component :is="iconFor(item).component"
                                   class="h-8 w-8 shrink-0"
                                   :class="iconFor(item).colorClass" />
                        <div class="min-w-0">
                            <div class="truncate font-mono text-sm font-semibold text-slate-900 dark:text-slate-100"
                                 :title="item.name">
                                {{ item.name }}
                            </div>
                            <div class="text-xs text-slate-500 dark:text-slate-400">
                                {{ isDir ? 'Klasör' : (item.mime || 'Dosya') }}
                            </div>
                        </div>
                    </div>

                    <!-- Property grid -->
                    <dl class="grid grid-cols-[110px_minmax(0,1fr)] gap-y-2 text-sm">
                        <dt class="text-slate-500 dark:text-slate-400">Boyut</dt>
                        <dd class="font-mono text-slate-800 dark:text-slate-100">{{ sizeDisplay }}</dd>

                        <dt class="text-slate-500 dark:text-slate-400">İzinler</dt>
                        <dd class="font-mono text-slate-800 dark:text-slate-100">{{ permsDisplay }}</dd>

                        <dt class="text-slate-500 dark:text-slate-400">Sahip</dt>
                        <dd class="font-mono text-slate-800 dark:text-slate-100">{{ ownerDisplay }}</dd>

                        <dt class="text-slate-500 dark:text-slate-400">Değiştirildi</dt>
                        <dd class="text-slate-800 dark:text-slate-100">{{ mtimeDisplay }}</dd>

                        <dt class="text-slate-500 dark:text-slate-400">Erişildi</dt>
                        <dd class="text-slate-800 dark:text-slate-100">{{ atimeDisplay }}</dd>

                        <dt class="text-slate-500 dark:text-slate-400">Oluşturuldu</dt>
                        <dd class="text-slate-800 dark:text-slate-100">{{ ctimeDisplay }}</dd>

                        <dt class="text-slate-500 dark:text-slate-400">MIME</dt>
                        <dd class="font-mono text-xs text-slate-800 dark:text-slate-100">{{ mimeDisplay }}</dd>

                        <dt class="text-slate-500 dark:text-slate-400">Tam Yol</dt>
                        <dd class="flex items-start gap-1.5">
                            <code class="block min-w-0 flex-1 break-all rounded bg-slate-100 px-2 py-1 font-mono text-[11px] text-slate-700 dark:bg-slate-800 dark:text-slate-200">{{ fullPath }}</code>
                            <button type="button"
                                    @click="copyFullPath"
                                    title="Yolu kopyala"
                                    class="shrink-0 rounded p-1 text-slate-400 hover:bg-slate-200 hover:text-slate-700 dark:hover:bg-slate-700 dark:hover:text-slate-200">
                                <ClipboardDocumentIcon class="h-4 w-4" />
                            </button>
                        </dd>
                    </dl>
                </div>

                <!-- Footer -->
                <div class="flex justify-end gap-2 border-t border-slate-200 bg-slate-50 px-5 py-3 dark:border-slate-700 dark:bg-slate-800/60">
                    <button type="button"
                            @click="close"
                            class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700">
                        Kapat
                    </button>
                </div>
            </div>
        </div>
    </Teleport>
</template>
