<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { usePageTitle } from '../composables/Core/usePageTitle';
import { useNavigate } from '../composables/Core/useNavigate';
import { useModal } from '../composables/Core/useModal';
import LoadingSpinner from '../Components/LoadingSpinner.vue';
import FileImage from '../Components/Core/FileImage.vue';
import BackButton from '../Components/Core/BackButton.vue';
import CardSimple from '../Components/Core/CardSimple.vue';

usePageTitle('Add Products to Store');

const props = defineProps({
    target: { type: String, default: null },
});

const { navigate } = useNavigate();
const modal = useModal();

const STEP = { PICK: 1, EDIT: 2 };
const step = ref(STEP.PICK);

const storeHash = computed(() => props.target);
const store = ref(null);

const loadingProducts = ref(false);
const loadingStore = ref(false);
const submitting = ref(false);
const error = ref(null);

const allProducts = ref([]);
const search = ref('');
const selected = ref({});
const rows = ref([]);

const bulkPrice = ref('');
const bulkAvailable = ref('');

const firstPhoto = (v) => Array.isArray(v) ? (v[0] || '') : (v || '');

const filteredProducts = computed(() => {
    const q = search.value.trim().toLowerCase();
    if (!q) return allProducts.value;
    return allProducts.value.filter((p) =>
        (p.name || '').toLowerCase().includes(q) ||
        (p.category || '').toLowerCase().includes(q) ||
        (p.subcategory || '').toLowerCase().includes(q)
    );
});

const selectedCount = computed(() => Object.values(selected.value).filter(Boolean).length);

const fetchStore = async () => {
    if (!storeHash.value) return;
    loadingStore.value = true;
    try {
        const { data } = await axios.post('/View/Store/Details/data', { target: storeHash.value });
        if (data?.success) store.value = data.data;
    } catch (e) {
        console.warn('Failed to fetch store details', e);
    } finally {
        loadingStore.value = false;
    }
};

const fetchProducts = async () => {
    loadingProducts.value = true;
    error.value = null;
    try {
        const { data } = await axios.post('/Products/GlobalList', {});
        if (data?.success && Array.isArray(data.products)) {
            allProducts.value = data.products;
        } else {
            error.value = 'Failed to load products';
        }
    } catch (e) {
        error.value = 'Failed to load products. Please try again.';
    } finally {
        loadingProducts.value = false;
    }
};

const toggleProduct = (hash) => {
    selected.value = { ...selected.value, [hash]: !selected.value[hash] };
};

const selectAllFiltered = () => {
    const next = { ...selected.value };
    for (const p of filteredProducts.value) next[p.hashkey] = true;
    selected.value = next;
};

const clearSelection = () => {
    selected.value = {};
};

const proceedToEdit = () => {
    const picks = allProducts.value.filter((p) => selected.value[p.hashkey]);
    if (picks.length === 0) {
        error.value = 'Pick at least one product to continue.';
        return;
    }
    error.value = null;
    rows.value = picks.map((p) => ({
        hashkey: p.hashkey,
        name: p.name,
        photourl: p.photourl,
        unitname: p.unitname,
        category: p.category,
        price: parseFloat(p.price) || 0,
        available: parseInt(p.available) || 0,
        global_price: parseFloat(p.price) || 0,
        global_available: parseInt(p.available) || 0,
        description: p.description || '',
    }));
    step.value = STEP.EDIT;
    window.scrollTo({ top: 0, behavior: 'smooth' });
};

const backToPick = () => {
    step.value = STEP.PICK;
    window.scrollTo({ top: 0, behavior: 'smooth' });
};

const applyBulkPrice = () => {
    const v = parseFloat(bulkPrice.value);
    if (isNaN(v) || v < 0) return;
    rows.value = rows.value.map((r) => ({ ...r, price: v }));
};

const applyBulkAvailable = () => {
    const v = parseInt(bulkAvailable.value);
    if (isNaN(v) || v < 0) return;
    rows.value = rows.value.map((r) => ({ ...r, available: v }));
};

const removeRow = (hash) => {
    rows.value = rows.value.filter((r) => r.hashkey !== hash);
    selected.value = { ...selected.value, [hash]: false };
    if (rows.value.length === 0) backToPick();
};

const submit = async () => {
    if (submitting.value) return;
    if (!storeHash.value) {
        error.value = 'No store specified.';
        return;
    }
    for (const r of rows.value) {
        if (!(r.price >= 0)) {
            error.value = `Invalid price for "${r.name}".`;
            return;
        }
        if (!(r.available >= 0)) {
            error.value = `Invalid availability for "${r.name}".`;
            return;
        }
    }
    submitting.value = true;
    error.value = null;
    const failures = [];
    for (const r of rows.value) {
        try {
            await axios.post('/Products/AssignToStore/', {
                target: r.hashkey,
                TargetStore: storeHash.value,
                price: parseFloat(r.price),
                available: parseInt(r.available),
                description: r.description || '',
            });
        } catch (e) {
            failures.push(r.name);
        }
    }
    submitting.value = false;

    if (failures.length === rows.value.length) {
        error.value = 'Failed to add any product. Please try again.';
        return;
    }

    modal.quickDismiss({
        title: 'Products Added',
        body: failures.length
            ? `Added ${rows.value.length - failures.length} of ${rows.value.length}. Failed: ${failures.join(', ')}.`
            : `Added ${rows.value.length} product(s) to ${store.value?.name || 'your store'}.`,
        onShown: () => {
            setTimeout(() => navigate({ page: 'ViewStoreMarket', props: { target: storeHash.value } }), 1100);
        },
    });
};

onMounted(() => {
    if (!storeHash.value) {
        error.value = 'No store specified. Pick a store from Manage Stores.';
        return;
    }
    fetchStore();
    fetchProducts();
});
</script>

<template>
    <div class="add-products-page pb-5">
        <div class="tf-container mt-4">
            <div class="d-flex align-items-center gap-2 mb-3">
                <BackButton />
                <h3 class="fw_6 mb-0">Add Products to Store</h3>
            </div>

            <CardSimple class="mb-3" :is-premium="false">
                <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                    <div>
                        <div class="text-muted smallest">Target store</div>
                        <div class="fw_6">{{ store?.name || (loadingStore ? 'Loading…' : '—') }}</div>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <span v-if="step === STEP.PICK" class="badge bg-soft-primary text-primary px-3 py-2 rounded-pill">
                            Step 1 of 2 · Pick products
                        </span>
                        <span v-else class="badge bg-soft-primary text-primary px-3 py-2 rounded-pill">
                            Step 2 of 2 · Set price & stock
                        </span>
                    </div>
                </div>
            </CardSimple>

            <div v-if="error" class="alert alert-danger mb-3">
                <i class="fas fa-exclamation-triangle me-2"></i>{{ error }}
            </div>

            <!-- Step 1: Picker -->
            <div v-if="step === STEP.PICK">
                <CardSimple class="mb-3" :is-premium="false">
                    <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between">
                        <div class="flex-grow-1" style="min-width: 220px;">
                            <input v-model="search" type="text" class="form-control"
                                placeholder="Search products by name, category…" />
                        </div>
                        <div class="d-flex gap-2">
                            <button class="btn btn-sm btn-outline-primary rounded-pill" @click="selectAllFiltered">
                                Select all shown
                            </button>
                            <button class="btn btn-sm btn-outline-secondary rounded-pill" @click="clearSelection"
                                :disabled="selectedCount === 0">
                                Clear
                            </button>
                        </div>
                    </div>
                </CardSimple>

                <div v-if="loadingProducts" class="text-center py-5">
                    <LoadingSpinner />
                </div>
                <div v-else-if="filteredProducts.length === 0" class="text-center py-5 text-muted">
                    <i class="fas fa-box-open fa-3x opacity-25 mb-3"></i>
                    <p class="mb-0">No products match your search.</p>
                </div>
                <div v-else class="row g-2">
                    <div v-for="p in filteredProducts" :key="p.hashkey" class="col-12 col-sm-6 col-lg-4">
                        <div class="product-pick-card" :class="{ picked: selected[p.hashkey] }"
                            @click="toggleProduct(p.hashkey)">
                            <div class="d-flex gap-3 align-items-center">
                                <div class="product-thumb">
                                    <FileImage :src="firstPhoto(p.photourl)"
                                        class="img-fluid rounded" alt="Product"
                                        fallback="https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/146710fe9ece.bin" />
                                </div>
                                <div class="flex-grow-1 min-w-0">
                                    <div class="d-flex align-items-center gap-2">
                                        <div class="fw_6 text-truncate" :title="p.name">{{ p.name }}</div>
                                    </div>
                                    <div class="text-muted smallest text-truncate">
                                        {{ p.category }}<span v-if="p.subcategory"> · {{ p.subcategory }}</span>
                                    </div>
                                    <div class="smallest">
                                        ₱{{ p.price }} <span class="text-muted">/ {{ p.unitname || 'unit' }}</span>
                                    </div>
                                </div>
                                <div class="form-check">
                                    <input type="checkbox" class="form-check-input" :checked="!!selected[p.hashkey]"
                                        @click.stop="toggleProduct(p.hashkey)" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="sticky-bottom-bar mt-4">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="text-muted small">
                            <strong>{{ selectedCount }}</strong> selected
                        </div>
                        <button class="btn btn-primary rounded-pill px-4" :disabled="selectedCount === 0"
                            @click="proceedToEdit">
                            Continue <i class="fas fa-arrow-right ms-1"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Step 2: Batch edit -->
            <div v-else>
                <CardSimple class="mb-3">
                    <div class="fw_6 mb-3">Bulk apply</div>
                    <div class="row g-3 align-items-end">
                        <div class="col-12 col-sm-5">
                            <label class="form-label smallest text-muted mb-1">Set all prices (₱)</label>
                            <div class="d-flex gap-2 align-items-center">
                                <input v-model="bulkPrice" type="number" min="0" step="0.01" class="form-control"
                                    placeholder="e.g. 50" />
                                <button class="btn btn-primary rounded-pill flex-shrink-0" @click="applyBulkPrice">
                                    Apply
                                </button>
                            </div>
                        </div>
                        <div class="col-12 col-sm-5">
                            <label class="form-label smallest text-muted mb-1">Set all availability</label>
                            <div class="d-flex gap-2 align-items-center">
                                <input v-model="bulkAvailable" type="number" min="0" step="1" class="form-control"
                                    placeholder="e.g. 100" />
                                <button class="btn btn-primary rounded-pill flex-shrink-0" @click="applyBulkAvailable">
                                    Apply
                                </button>
                            </div>
                        </div>
                        <div class="col-12 col-sm-2 d-flex align-items-end">
                            <button class="btn btn-outline-secondary rounded-pill w-100" @click="backToPick">
                                <i class="fas fa-arrow-left me-1"></i> Back
                            </button>
                        </div>
                    </div>
                </CardSimple>

                <div class="table-responsive">
                    <table class="table align-middle">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th style="width: 160px;">Price (₱)</th>
                                <th style="width: 160px;">Available</th>
                                <th style="width: 60px;"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="r in rows" :key="r.hashkey">
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <div class="product-thumb-sm">
                                            <FileImage :src="firstPhoto(r.photourl)"
                                                class="img-fluid rounded" alt="Product"
                                                fallback="https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/146710fe9ece.bin" />
                                        </div>
                                        <div class="min-w-0">
                                            <div class="fw_6 text-truncate" :title="r.name">{{ r.name }}</div>
                                            <div class="text-muted smallest">
                                                global ₱{{ r.global_price }} · {{ r.global_available }} {{ r.unitname || 'unit' }}
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <input v-model.number="r.price" type="number" min="0" step="0.01"
                                        class="form-control form-control-sm" />
                                </td>
                                <td>
                                    <input v-model.number="r.available" type="number" min="0" step="1"
                                        class="form-control form-control-sm" />
                                </td>
                                <td class="text-end">
                                    <button class="btn btn-sm btn-icon btn-outline-danger" title="Remove"
                                        @click="removeRow(r.hashkey)">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="sticky-bottom-bar mt-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="text-muted small"><strong>{{ rows.length }}</strong> product(s) to add</div>
                        <button class="btn btn-primary rounded-pill px-4" :disabled="submitting || rows.length === 0"
                            @click="submit">
                            <span v-if="submitting"><LoadingSpinner small /></span>
                            <span v-else><i class="fas fa-check me-1"></i> Add to Store</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.product-pick-card {
    border: 1px solid var(--border-color, rgba(0, 0, 0, 0.08));
    border-radius: 12px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.15s ease;
    background: var(--bg-card, #fff);
    min-height: 84px;
}

.row.g-2 {
    align-items: flex-start;
}

.product-pick-card:hover {
    border-color: var(--primary, #4caf50);
    transform: translateY(-1px);
}

.product-pick-card.picked {
    border-color: var(--primary, #4caf50);
    box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.15);
}

.product-thumb {
    width: 56px;
    height: 56px;
    flex-shrink: 0;
    overflow: hidden;
    border-radius: 8px;
    background: rgba(0, 0, 0, 0.04);
}

.product-thumb :deep(img) {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-thumb-sm {
    width: 40px;
    height: 40px;
    flex-shrink: 0;
    overflow: hidden;
    border-radius: 6px;
    background: rgba(0, 0, 0, 0.04);
}

.product-thumb-sm :deep(img) {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.sticky-bottom-bar {
    position: sticky;
    bottom: 12px;
    background: var(--bg-card, #fff);
    border: 1px solid var(--border-color, rgba(0, 0, 0, 0.08));
    border-radius: 14px;
    padding: 12px 16px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
    z-index: 5;
}

.min-w-0 {
    min-width: 0;
}
</style>
