<script setup>
import {computed, ref} from 'vue'

const props = defineProps({
    files: {
        type: Array,
        default: () => []
    },
    plans: {
        type: Array,
        default: () => []
    },
    pricingMode: {
        type: String,
        default: 'simple'
    },
    // Bundle mode props
    bundleMode: {
        type: Boolean,
        default: false
    },
    bundleItems: {
        type: Array,
        default: () => []  // [{ product_id, product_name, plan_ids: [] }]
    },
    availableProducts: {
        type: Array,
        default: () => []  // [{ id, name }]
    }
})

const emit = defineEmits([
    // File mode
    'add-file', 'update-file', 'remove-file',
    // Bundle mode
    'update-bundle-items'
])

// ─── File upload (existing behaviour) ────────────────────────────────────────

const isUploading = ref(false)
const fileInput   = ref(null)

const triggerUpload = () => fileInput.value.click()

const handleFileSelect = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    const formData = new FormData()
    formData.append('file', file)
    formData.append('disk', 'local')

    isUploading.value = true

    try {
        const response = await axios.post('/ch-admin/media', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })

        const mediaId = response.data

        const newFile = {
            id:       crypto.randomUUID(),
            media_id: mediaId,
            name:     file.name,
            size:     (file.size / 1024 / 1024).toFixed(2) + ' MB',
            date:     new Date().toLocaleDateString(),
            plan_ids: props.plans.length === 1 ? [props.plans[0].id] : []
        }

        emit('add-file', newFile)

    } catch (error) {
        console.error('Upload failed:', error)
        alert('Upload failed: ' + (error.response?.data?.errors || error.message))
    } finally {
        isUploading.value = false
        event.target.value = ''
    }
}

const togglePlan = (fileIndex, planId) => {
    const file       = props.files[fileIndex]
    const current    = file.plan_ids || []
    const newPlanIds = current.includes(planId)
        ? current.filter(pid => pid !== planId)
        : [...current, planId]

    emit('update-file', { index: fileIndex, file: { ...file, plan_ids: newPlanIds } })
}

const removeFile = (index) => {
    const msg = props.pricingMode === 'variable'
        ? 'Delete this file? It will be removed from all plans.'
        : 'Delete this file?'
    if (confirm(msg)) emit('remove-file', index)
}

// File assign modal
const showAssignModal  = ref(false)
const activeFileIndex  = ref(null)

const openAssignModal  = (i) => { activeFileIndex.value = i;    showAssignModal.value = true  }
const closeAssignModal = ()  => { activeFileIndex.value = null; showAssignModal.value = false }

const togglePlanInModal = (planId) => {
    if (activeFileIndex.value !== null) togglePlan(activeFileIndex.value, planId)
}

// ─── Bundle product picker ────────────────────────────────────────────────────

const productSearch = ref('')

const filteredAvailable = computed(() => {
    const q = productSearch.value.toLowerCase()
    return props.availableProducts.filter(p =>
        p.name.toLowerCase().includes(q) &&
        !props.bundleItems.some(b => b.product_id === p.id)
    )
})

const addBundleProduct = (product) => {
    const updated = [
        ...props.bundleItems,
        {
            product_id:   product.id,
            product_name: product.name,
            plan_ids:     props.plans.length === 1 ? [props.plans[0].id] : []
        }
    ]
    emit('update-bundle-items', updated)
    productSearch.value = ''
}

const removeBundleProduct = (index) => {
    const updated = props.bundleItems.filter((_, i) => i !== index)
    emit('update-bundle-items', updated)
}

// Bundle assign modal
const showBundleAssignModal  = ref(false)
const activeBundleIndex      = ref(null)

const openBundleAssignModal  = (i) => { activeBundleIndex.value = i;    showBundleAssignModal.value = true  }
const closeBundleAssignModal = ()  => { activeBundleIndex.value = null; showBundleAssignModal.value = false }

const togglePlanForBundleProduct = (planId) => {
    if (activeBundleIndex.value === null) return
    const item    = props.bundleItems[activeBundleIndex.value]
    const current = item.plan_ids || []
    const updated = current.includes(planId)
        ? current.filter(id => id !== planId)
        : [...current, planId]

    const newItems = props.bundleItems.map((b, i) =>
        i === activeBundleIndex.value ? { ...b, plan_ids: updated } : b
    )
    emit('update-bundle-items', newItems)
}
</script>

<template>
    <div class="card rounded-xl border-0 p-4">

        <!-- ── FILE UPLOAD MODE ─────────────────────────────────────── -->
        <template v-if="!bundleMode">
            <input type="file" ref="fileInput" class="d-none" @change="handleFileSelect">

            <div class="d-flex align-items-center justify-content-between mb-4">
                <div>
                    <h2 class="h6 fw-semibold d-flex align-items-center gap-2 mb-1">
                        <span class="bg-primary-subtle text-primary p-1 rounded-3 d-flex">
                            <span class="material-icons fs-5">folder_open</span>
                        </span>
                        Global Files & Deliverables
                    </h2>
                    <p class="small text-secondary mb-0">Upload assets here, then assign them to specific plans.</p>
                </div>
                <button class="btn btn-primary d-flex align-items-center gap-2 btn-sm px-3 shadow-sm"
                        @click="triggerUpload" :disabled="isUploading">
                    <span v-if="isUploading" class="spinner-border spinner-border-sm" role="status"></span>
                    <span v-else class="material-icons fs-6">cloud_upload</span>
                    {{ isUploading ? 'Uploading...' : 'Upload File' }}
                </button>
            </div>

            <!-- Drop area -->
            <div class="border border-2 border-dashed rounded-xl p-4 mb-4 text-center cursor-pointer hover-border-primary bg-light bg-opacity-25 transition"
                 @click="triggerUpload">
                <div class="bg-white rounded-circle p-2 shadow-sm d-inline-flex mb-2">
                    <span class="material-icons text-primary">cloud_upload</span>
                </div>
                <p class="fw-medium text-dark mb-0 small">Click to upload or drag and drop</p>
                <p class="x-small text-secondary mb-0">ZIP, PDF, MP4 up to 10GB</p>
            </div>

            <!-- Empty state -->
            <div v-if="files.length === 0" class="text-center py-4">
                <span class="small text-secondary">No files uploaded yet.</span>
            </div>

            <!-- File list -->
            <div v-else class="d-flex flex-column gap-2">
                <div v-for="(file, index) in files" :key="file.id"
                     class="d-flex flex-column p-3 border rounded-lg bg-white shadow-sm">

                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <div class="d-flex align-items-center gap-3">
                            <div class="icon-square bg-light text-primary rounded p-2">
                                <span class="material-icons">description</span>
                            </div>
                            <div>
                                <div class="fw-medium text-dark text-sm">{{ file.name }}</div>
                                <div class="x-small text-secondary">{{ file.size }} • {{ file.date }}</div>
                            </div>
                        </div>
                        <button class="btn btn-link text-secondary p-0 hover-text-danger" @click="removeFile(index)">
                            <span class="material-icons">delete</span>
                        </button>
                    </div>

                    <!-- Plan availability -->
                    <div v-if="plans.length > 1 || pricingMode === 'variable'" class="mt-2 pt-2 border-top">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center gap-2">
                                <span class="x-small fw-bold text-uppercase text-secondary">Availability:</span>
                                <span v-if="!file.plan_ids || file.plan_ids.length === 0"
                                      class="badge bg-danger-subtle text-danger d-flex align-items-center gap-1">
                                    <span class="material-icons" style="font-size:14px !important;">warning</span>
                                    Unassigned
                                </span>
                                <div v-else class="d-flex flex-wrap gap-1">
                                    <span v-for="planId in file.plan_ids" :key="planId"
                                          class="badge bg-success-subtle text-success border border-success-subtle p-1">
                                        {{ plans.find(p => p.id === planId)?.name || 'Unknown Plan' }}
                                    </span>
                                </div>
                            </div>
                            <button class="btn btn-secondary btn-sm d-flex align-items-center gap-1 py-0 px-3"
                                    @click="openAssignModal(index)"
                                    style="height:28px;font-size:13px;">
                                <span class="material-icons fs-6" style="font-size:16px !important;">link</span>
                                Assign
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- File assign modal -->
            <div v-if="showAssignModal"
                 class="modal-backdrop bg-dark bg-opacity-50 position-fixed top-0 start-0 w-100 h-100"
                 style="z-index:1040;"></div>
            <div v-if="showAssignModal" class="modal d-block" tabindex="-1" style="z-index:1050;">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content shadow-lg border-0 rounded-xl">
                        <div class="modal-header border-0 pb-0">
                            <h5 class="modal-title fw-semibold">Assign to Plans</h5>
                            <button type="button" class="btn-close" @click="closeAssignModal"></button>
                        </div>
                        <div class="modal-body">
                            <p class="small text-secondary mb-3">Select which pricing plans include this file:</p>
                            <div>
                                <div v-for="plan in plans" :key="plan.id"
                                     class="d-flex align-items-center gap-3 p-3 border rounded bg-light hover-shadow cursor-pointer mb-2"
                                     @click="togglePlanInModal(plan.id)">
                                    <input class="form-check-input m-0 flex-shrink-0" type="checkbox"
                                           :checked="files[activeFileIndex]?.plan_ids?.includes(plan.id)"
                                           @click.stop="togglePlanInModal(plan.id)"
                                           style="width:1.2em;height:1.2em;">
                                    <label class="fw-medium w-100 cursor-pointer mb-0" @click.stop>{{ plan.name }}</label>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer border-0 pt-0">
                            <button type="button" class="btn btn-primary" @click="closeAssignModal">Done</button>
                        </div>
                    </div>
                </div>
            </div>
        </template>

        <!-- ── BUNDLE PRODUCT PICKER MODE ──────────────────────────── -->
        <template v-else>
            <div class="d-flex align-items-center justify-content-between mb-4">
                <div>
                    <h2 class="h6 fw-semibold d-flex align-items-center gap-2 mb-1">
                        <span class="bg-warning-subtle text-warning p-1 rounded-3 d-flex">
                            <span class="material-icons fs-5">inventory_2</span>
                        </span>
                        Included Products
                    </h2>
                    <p class="small text-secondary mb-0">
                        Select which products subscribers get access to, then assign them to specific plans.
                    </p>
                </div>
            </div>

            <!-- Search -->
            <div class="input-group mb-3">
                <span class="input-group-text bg-white border-end-0">
                    <span class="material-icons text-secondary fs-6">search</span>
                </span>
                <input type="text" class="form-control border-start-0 ps-0"
                       placeholder="Search products to add..."
                       v-model="productSearch">
            </div>

            <!-- Search results -->
            <div v-if="productSearch && filteredAvailable.length > 0"
                 class="border rounded-lg bg-white shadow-sm mb-3"
                 style="max-height:200px;overflow-y:auto;">
                <div v-for="product in filteredAvailable" :key="product.id"
                     class="d-flex align-items-center justify-content-between p-3 border-bottom cursor-pointer hover-bg-light"
                     @click="addBundleProduct(product)">
                    <span class="small fw-medium">{{ product.name }}</span>
                    <span class="material-icons text-primary fs-6">add_circle_outline</span>
                </div>
            </div>
            <div v-if="productSearch && filteredAvailable.length === 0"
                 class="text-center small text-secondary py-2 mb-3">
                No matching products found.
            </div>

            <!-- Empty state -->
            <div v-if="bundleItems.length === 0" class="text-center py-4">
                <span class="material-icons fs-1 text-secondary opacity-25 mb-2 d-block">inventory_2</span>
                <p class="small text-secondary mb-0">No products added yet. Search above to include products in this bundle.</p>
            </div>

            <!-- Selected products list -->
            <div v-else class="d-flex flex-column gap-2">
                <div v-for="(item, index) in bundleItems" :key="item.product_id"
                     class="d-flex flex-column p-3 border rounded-lg bg-white shadow-sm">

                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <div class="d-flex align-items-center gap-3">
                            <div class="icon-square bg-warning-subtle text-warning rounded p-2">
                                <span class="material-icons">inventory_2</span>
                            </div>
                            <div class="fw-medium text-dark">{{ item.product_name }}</div>
                        </div>
                        <button class="btn btn-link text-secondary p-0 hover-text-danger"
                                @click="removeBundleProduct(index)">
                            <span class="material-icons">delete</span>
                        </button>
                    </div>

                    <!-- Plan assignment (only when multiple plans) -->
                    <div v-if="plans.length > 1" class="mt-2 pt-2 border-top">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center gap-2">
                                <span class="x-small fw-bold text-uppercase text-secondary">Available in:</span>
                                <span v-if="!item.plan_ids || item.plan_ids.length === 0"
                                      class="badge bg-danger-subtle text-danger d-flex align-items-center gap-1">
                                    <span class="material-icons" style="font-size:14px !important;">warning</span>
                                    Unassigned
                                </span>
                                <div v-else class="d-flex flex-wrap gap-1">
                                    <span v-for="planId in item.plan_ids" :key="planId"
                                          class="badge bg-success-subtle text-success border border-success-subtle p-1">
                                        {{ plans.find(p => p.id === planId)?.name || 'Unknown Plan' }}
                                    </span>
                                </div>
                            </div>
                            <button class="btn btn-secondary btn-sm d-flex align-items-center gap-1 py-0 px-3"
                                    @click="openBundleAssignModal(index)"
                                    style="height:28px;font-size:13px;">
                                <span class="material-icons fs-6" style="font-size:16px !important;">link</span>
                                Assign
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Bundle assign modal -->
            <div v-if="showBundleAssignModal"
                 class="modal-backdrop bg-dark bg-opacity-50 position-fixed top-0 start-0 w-100 h-100"
                 style="z-index:1040;"></div>
            <div v-if="showBundleAssignModal" class="modal d-block" tabindex="-1" style="z-index:1050;">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content shadow-lg border-0 rounded-xl">
                        <div class="modal-header border-0 pb-0">
                            <h5 class="modal-title fw-semibold">Assign to Plans</h5>
                            <button type="button" class="btn-close" @click="closeBundleAssignModal"></button>
                        </div>
                        <div class="modal-body">
                            <p class="small text-secondary mb-3">
                                Select which plans include
                                <strong>{{ activeBundleIndex !== null ? bundleItems[activeBundleIndex]?.product_name : '' }}</strong>:
                            </p>
                            <div>
                                <div v-for="plan in plans" :key="plan.id"
                                     class="d-flex align-items-center gap-3 p-3 border rounded bg-light hover-shadow cursor-pointer mb-2"
                                     @click="togglePlanForBundleProduct(plan.id)">
                                    <input class="form-check-input m-0 flex-shrink-0" type="checkbox"
                                           :checked="activeBundleIndex !== null && bundleItems[activeBundleIndex]?.plan_ids?.includes(plan.id)"
                                           @click.stop="togglePlanForBundleProduct(plan.id)"
                                           style="width:1.2em;height:1.2em;">
                                    <label class="fw-medium w-100 cursor-pointer mb-0" @click.stop>{{ plan.name }}</label>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer border-0 pt-0">
                            <button type="button" class="btn btn-primary" @click="closeBundleAssignModal">Done</button>
                        </div>
                    </div>
                </div>
            </div>
        </template>

    </div>
</template>
