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

const { navigate } = useNavigate()
const modal = useModal()
usePageTitle('Batch Add Stores')

const stores = ref([
    { name: '', description: '', address: '', category: '', subcategory: '', owner_hash: '' }
])

const loading = ref(false)
const saving = ref(false)
const categories = ref([])
const owners = ref([])

const addRow = () => {
    stores.value.push({ name: '', description: '', address: '', category: '', subcategory: '', owner_hash: '' })
}

const removeRow = (index) => {
    if (stores.value.length > 1) {
        stores.value.splice(index, 1)
    }
}

const fetchData = async () => {
    try {
        const [catRes, ownerRes] = await Promise.all([
            axios.post('/Store/New/Category/Datalist'),
            axios.post('/admin/user/list/numbers/hash')
        ])

        if (catRes.data) categories.value = catRes.data
        if (ownerRes.data) owners.value = ownerRes.data
    } catch (err) {
        console.error('Error fetching store metadata:', err)
    }
}

const saveStores = async () => {
    const invalid = stores.value.some(s => !s.name || !s.description || !s.address)
    if (invalid) {
        modal.open({
            title: 'Validation Error',
            body: 'Please fill in all required fields (Name, Description, Address) for all rows.'
        })
        return
    }

    saving.value = true
    try {
        const response = await axios.post('/admin/batch/stores', { stores: stores.value })
        if (response.data && response.data.success) {
            modal.open({
                title: 'Success',
                body: `Successfully added ${response.data.count} stores.`,
                onClose: () => navigate({ page: 'ManageStoresAdmin' })
            })
        }
    } catch (err) {
        console.error('Error saving batch stores:', err)
        const errorMessage = err.response?.data?.errors
            ? err.response.data.errors.join('<br>')
            : (err.response?.data?.message || 'Failed to save stores.')

        modal.open({
            title: 'Error',
            body: errorMessage
        })
    } finally {
        saving.value = false
    }
}

onMounted(() => {
    fetchData()
})
</script>

<template>
    <div class="batch-add-page pb-5">
        <div class="tf-container mt-4">
            <div class="mb-3">
                <BackButton to="ManageStoresAdmin" />
            </div>

            <div class="mb-4">
                <h3 class="fw_6 mb-1">Batch Add Stores</h3>
                <p class="text-muted small mb-0">Create multiple stores at once. Ideal for large-scale onboarding.</p>
            </div>

            <div class="d-grid mb-3">
                <button @click="addRow" class="btn btn-outline-primary rounded-pill">
                    <i class="fas fa-plus-circle me-2"></i> Add Store
                </button>
            </div>

            <div class="row g-4">
                <div v-for="(store, index) in stores" :key="index" class="col-md-6 col-lg-4">
                    <div class="leaf-card p-3 bg-white rounded-3 border position-relative h-100">
                        <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                            <span class="badge bg-primary rounded-pill">#{{ index + 1 }}</span>
                            <button @click="removeRow(index)" class="btn btn-link text-danger p-0 border-0"
                                :disabled="stores.length <= 1"><i class="fas fa-times-circle"></i></button>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold text-muted mb-1">Store Name *</label>
                            <input v-model="store.name" type="text" class="form-control form-control-sm" placeholder="Store name">
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold text-muted mb-1">Address *</label>
                            <input v-model="store.address" type="text" class="form-control form-control-sm" placeholder="Complete address">
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold text-muted mb-1">Description *</label>
                            <input v-model="store.description" type="text" class="form-control form-control-sm" placeholder="Short description">
                        </div>

                        <div class="row g-2 mb-2">
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted mb-1">Category</label>
                                <select v-model="store.category" class="form-select form-select-sm">
                                    <option value="">Select Category</option>
                                    <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
                                </select>
                            </div>
                            <div class="col-6">
                                <label class="form-label small fw-bold text-muted mb-1">Subcategory</label>
                                <input v-model="store.subcategory" type="text" class="form-control form-control-sm" placeholder="Subcategory">
                            </div>
                        </div>

                        <div class="mb-2">
                            <label class="form-label small fw-bold text-muted mb-1">Owner</label>
                            <select v-model="store.owner_hash" class="form-select form-select-sm">
                                <option value="">System Default</option>
                                <option v-for="owner in owners" :key="owner.hashkey" :value="owner.hashkey">{{ owner.name }} ({{ owner.username }})</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="d-grid mt-4">
                <button @click="addRow" class="btn btn-outline-primary rounded-pill px-4 fw-semibold">
                    <i class="fas fa-plus-circle me-2"></i> Add Another Store
                </button>
            </div>

            <div class="d-grid mt-3 pt-3 border-top">
                <button @click="saveStores" :disabled="saving" class="btn btn-primary rounded-pill px-4 fw-semibold">
                    <i class="fas fa-save me-2"></i>
                    {{ saving ? 'Saving...' : 'Save All Stores' }}
                </button>
            </div>
        </div>
    </div>
</template>

<style scoped>
.batch-add-page {
    background: var(--bg-primary);
    min-height: 100vh;
}
.leaf-card { transition: box-shadow 0.15s ease, transform 0.15s ease; }
.leaf-card:hover { box-shadow: 0 4px 12px rgba(13,110,253,0.08); transform: translateY(-2px); }
:global(.dark-mode) .leaf-card { background-color: var(--bg-secondary) !important; border-color: var(--border-color) !important; }
:global(.dark-mode) .form-control, :global(.dark-mode) .form-select {
    background-color: var(--bg-secondary) !important;
    color: var(--text-primary);
    border-color: var(--border-color);
}
</style>
