<template>
    <Teleport to="body">
        <div class="modal-overlay" :class="{ 'is-open': open }" @click.self="close">
            <div class="modal" style="width:820px;max-width:96vw">

                <!-- Header -->
                <div class="modal-header">
                    <div>
                        <h3 class="modal-title">Media Library</h3>
                        <p class="modal-subtitle">Reuse a file you've uploaded before, or upload a new one.</p>
                    </div>
                    <button class="modal-close" @click="close" aria-label="Close">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                    </button>
                </div>

                <!-- Body -->
                <div class="modal-body" style="background:#f9fafb;display:flex;flex-direction:column;gap:14px;min-height:420px">

                    <div class="ml-tabs">
                        <button :class="['ml-tab', tab === 'library' && 'is-active']" @click="tab = 'library'">Library</button>
                        <button :class="['ml-tab', tab === 'upload' && 'is-active']" @click="tab = 'upload'">Upload New</button>
                    </div>

                    <!-- LIBRARY TAB -->
                    <template v-if="tab === 'library'">
                        <div class="ml-toolbar">
                            <input
                                type="text"
                                class="form-input"
                                v-model="search"
                                placeholder="Search files…"
                                style="max-width:260px"
                                @input="debouncedSearch"
                            >
                            <div class="ml-type-filter">
                                <button
                                    v-for="opt in typeOptions"
                                    :key="opt.value"
                                    :class="['ml-filter-btn', activeType === opt.value && 'is-active']"
                                    @click="setType(opt.value)"
                                >{{ opt.label }}</button>
                            </div>
                        </div>

                        <div v-if="loading && items.length === 0" class="ml-empty">Loading…</div>
                        <div v-else-if="items.length === 0" class="ml-empty">No files yet. Switch to "Upload New" to add one.</div>

                        <div v-else class="ml-grid">
                            <div
                                v-for="item in items"
                                :key="item.id"
                                class="ml-item"
                                :class="{ 'is-selected': selectedId === item.id }"
                                @click="selectedId = item.id"
                                @dblclick="choose(item)"
                            >
                                <div class="ml-thumb">
                                    <img v-if="item.type === 'image'" :src="item.url" :alt="item.original_name">
                                    <svg v-else-if="item.type === 'video'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="28" height="28"><path d="m10 8 6 4-6 4V8z"/><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
                                    <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="28" height="28"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>
                                    <button class="ml-delete-btn" title="Delete" @click.stop="remove(item)">
                                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="12" height="12"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                                    </button>
                                </div>
                                <div class="ml-item-name" :title="item.original_name">{{ item.original_name }}</div>
                            </div>
                        </div>

                        <button v-if="hasMore" class="btn btn-outline btn-sm" style="align-self:center" :disabled="loading" @click="loadMore">
                            {{ loading ? 'Loading…' : 'Load more' }}
                        </button>
                    </template>

                    <!-- UPLOAD TAB -->
                    <template v-else>
                        <div
                            class="ml-dropzone"
                            :class="{ 'is-dragover': dragOver }"
                            @dragover.prevent="dragOver = true"
                            @dragleave.prevent="dragOver = false"
                            @drop.prevent="onDrop"
                            @click="fileInputRef?.click()"
                        >
                            <input ref="fileInputRef" type="file" style="display:none" :accept="accept" @change="onFileSelected">
                            <template v-if="uploading">
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="24" height="24" class="cw-spin">
                                    <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
                                </svg>
                                <span>Uploading…</span>
                            </template>
                            <template v-else>
                                <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="m18 9-6-6-6 6"/><path d="M12 3v14"/><path d="M5 21h14"/></svg>
                                <span>Click or drag a file here to upload</span>
                            </template>
                        </div>
                        <p v-if="uploadError" class="field-error">{{ uploadError }}</p>
                    </template>

                </div>

                <!-- Footer -->
                <div class="modal-footer" style="justify-content:flex-end;gap:10px">
                    <button class="btn btn-outline" @click="close">Cancel</button>
                    <button class="btn btn-primary" :disabled="!selectedId" @click="chooseSelected">Select</button>
                </div>

            </div>
        </div>
    </Teleport>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';

const props = defineProps({
    open: { type: Boolean, default: false },
    // Restricts the library filter + upload accept to one type ('image' | 'video' | null for all)
    type: { type: String, default: null },
    // Tag stored on new uploads (e.g. 'campaign-image', 'business-logo', 'library')
    collection: { type: String, default: 'library' },
});

const emit = defineEmits(['close', 'select']);

const tab        = ref('library');
const items       = ref([]);
const loading     = ref(false);
const search      = ref('');
const activeType  = ref(props.type);
const page        = ref(1);
const hasMore     = ref(false);
const selectedId  = ref(null);

const uploading   = ref(false);
const uploadError = ref('');
const dragOver    = ref(false);
const fileInputRef = ref(null);

const typeOptions = [
    { value: null,      label: 'All' },
    { value: 'image',   label: 'Images' },
    { value: 'video',   label: 'Videos' },
    { value: 'document', label: 'Documents' },
];

const accept = props.type === 'image'
    ? 'image/jpeg,image/png,image/gif,image/webp,image/svg+xml'
    : props.type === 'video'
        ? 'video/mp4,video/webm,video/ogg,video/quicktime'
        : '*/*';

let searchTimer = null;
function debouncedSearch() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => fetchItems(1), 350);
}

watch(() => props.open, (isOpen) => {
    if (isOpen) {
        tab.value = 'library';
        selectedId.value = null;
        activeType.value = props.type;
        fetchItems(1);
    }
});

function setType(value) {
    activeType.value = value;
    fetchItems(1);
}

async function fetchItems(targetPage) {
    loading.value = true;
    try {
        const { data } = await window.axios.get(window.route('media.index'), {
            params: {
                type: activeType.value || undefined,
                search: search.value || undefined,
                page: targetPage,
            },
        });
        items.value = targetPage === 1 ? data.data : [...items.value, ...data.data];
        hasMore.value = data.current_page < data.last_page;
        page.value = data.current_page;
    } finally {
        loading.value = false;
    }
}

function loadMore() {
    fetchItems(page.value + 1);
}

function choose(item) {
    emit('select', item);
    close();
}

function chooseSelected() {
    const item = items.value.find(i => i.id === selectedId.value);
    if (item) choose(item);
}

async function remove(item) {
    if (!confirm(`Delete "${item.original_name}"? This can't be undone.`)) return;
    await window.axios.delete(window.route('media.destroy', item.id));
    items.value = items.value.filter(i => i.id !== item.id);
    if (selectedId.value === item.id) selectedId.value = null;
}

function onDrop(e) {
    dragOver.value = false;
    const file = e.dataTransfer.files?.[0];
    if (file) upload(file);
}

function onFileSelected(e) {
    const file = e.target.files?.[0];
    if (file) upload(file);
    e.target.value = '';
}

async function upload(file) {
    uploading.value = true;
    uploadError.value = '';
    try {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('collection', props.collection);
        const { data } = await window.axios.post(window.route('media.store'), formData, {
            headers: { 'Content-Type': 'multipart/form-data' },
        });
        choose(data);
    } catch (err) {
        uploadError.value = err.response?.data?.message || 'Upload failed. Please try again.';
    } finally {
        uploading.value = false;
    }
}

function close() {
    emit('close');
}
</script>

<style scoped>
.ml-tabs { display: flex; gap: 4px; border-bottom: 1px solid #e5e7eb; }
.ml-tab {
    border: none; background: transparent; cursor: pointer;
    padding: 8px 14px; font-size: 13px; font-weight: 500; color: #6b7280;
    border-bottom: 2px solid transparent; margin-bottom: -1px;
}
.ml-tab.is-active { color: #111827; border-bottom-color: #7c3aed; }

.ml-toolbar { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
.ml-type-filter { display: flex; gap: 4px; }
.ml-filter-btn {
    border: 1px solid #e5e7eb; background: #fff; cursor: pointer;
    padding: 5px 10px; font-size: 12px; border-radius: 6px; color: #4b5563;
}
.ml-filter-btn.is-active { background: #111827; border-color: #111827; color: #fff; }

.ml-empty { flex: 1; display: flex; align-items: center; justify-content: center; color: #9ca3af; font-size: 13px; padding: 40px 0; }

.ml-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
    gap: 10px;
    max-height: 340px;
    overflow-y: auto;
    padding: 2px;
}
.ml-item { cursor: pointer; border-radius: 8px; }
.ml-thumb {
    position: relative;
    width: 100%; aspect-ratio: 1;
    border: 2px solid transparent;
    border-radius: 8px;
    background: #fff;
    display: flex; align-items: center; justify-content: center;
    overflow: hidden;
    color: #9ca3af;
}
.ml-item.is-selected .ml-thumb { border-color: #7c3aed; }
.ml-thumb img { width: 100%; height: 100%; object-fit: cover; }
.ml-item-name {
    font-size: 11px; color: #6b7280; margin-top: 4px;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.ml-delete-btn {
    position: absolute; top: 4px; right: 4px;
    width: 20px; height: 20px; border-radius: 50%;
    border: none; background: rgba(17,24,39,.65); color: #fff;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; opacity: 0; transition: opacity 120ms;
}
.ml-thumb:hover .ml-delete-btn { opacity: 1; }

.ml-dropzone {
    flex: 1;
    display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
    border: 2px dashed #d1d5db; border-radius: 10px;
    color: #6b7280; font-size: 13px;
    cursor: pointer; min-height: 260px;
    transition: border-color 120ms, background 120ms;
}
.ml-dropzone.is-dragover { border-color: #7c3aed; background: #f5f3ff; }

.field-error { font-size: 12px; color: #ef4444; }
</style>
