<script setup>
import { usePageTitle } from '../composables/Core/usePageTitle';
usePageTitle('Create Store');

import { ref, computed, onMounted, watch } from 'vue';
import axios from 'axios';
import { useNavigate } from '../composables/Core/useNavigate.js';
import { useAuth } from '../composables/Core/useAuth.js';
import LoadingSpinner from '../Components/LoadingSpinner.vue';
import CardSimple from '../Components/Core/CardSimple.vue';
import Dropzone from '../Components/Core/Dropzone.vue';
import { useFileUpload } from '../composables/useFileUpload.js';
import { usePrefetchStore } from '../stores/prefetch';

const prefetchStore = usePrefetchStore();

const { navigate } = useNavigate();
const { isStoreOwner } = useAuth();
const { uploadFile, removeHash, photoHashes } = useFileUpload({ 
  category: 'StoreMarket',
  maxSizeMB: 10
});

const storeName = ref('');
const description = ref('');
const category = ref('');
const subcategory = ref('');
const categories = ref([]);
const subcategories = ref([]);
const address = ref('');
const owner = ref('');
const managers = ref([]);
const cooperatives = ref([]);
const cooperativeOptions = ref([]);
const cooperativeSearch = ref('');
const status = ref('active');
const remarks = ref('');
const loading = ref(false);
const showSuccessState = ref(false);
const showSuccessAnimation = ref(false);
const error = ref(null);
const successMessage = ref('');


const users = ref([]);
const userSearch = ref('');
const filteredUsers = computed(() => {
    if (!userSearch.value) return users.value;
    return users.value.filter(u => 
        u.name.toLowerCase().includes(userSearch.value.toLowerCase()) || 
        u.username.toLowerCase().includes(userSearch.value.toLowerCase())
    );
});

const fetchCategories = async () => {
    try {
        const response = await axios.post('/Store/New/Category/Datalist', {});
        if (response.data && Array.isArray(response.data)) {
            categories.value = response.data.map(item => ({
                label: typeof item === 'string' ? item : (item[1] || item[0]),
                value: typeof item === 'string' ? item : item[0]
            }));
        }
    } catch (error) {
        console.error('Failed to fetch categories:', error);
    }
};

const fetchSubcategories = async () => {
    if (!category.value) {
        subcategories.value = [];
        return;
    }
    try {
        const response = await axios.post('/Store/New/SubCategory/Datalist', { 
            category: category.value 
        });
        if (response.data && Array.isArray(response.data)) {
            subcategories.value = response.data.map(item => ({
                label: typeof item === 'string' ? item : (item[1] || item[0]),
                value: typeof item === 'string' ? item : item[0]
            }));
        }
    } catch (error) {
        console.error('Failed to fetch subcategories:', error);
    }
};

const handleCategoryChange = () => {
    subcategory.value = '';
    fetchSubcategories();
};

const filteredCooperatives = computed(() => {
    if (!cooperativeSearch.value) return cooperativeOptions.value;
    const q = cooperativeSearch.value.toLowerCase();
    return cooperativeOptions.value.filter(c =>
        (c.name || '').toLowerCase().includes(q) ||
        (c.cooperative_type || '').toLowerCase().includes(q)
    );
});

const fetchCooperatives = async () => {
    try {
        const response = await axios.post('/Store/Cooperatives/List', {});
        if (response.data && response.data.success && Array.isArray(response.data.data)) {
            cooperativeOptions.value = response.data.data;
        }
    } catch (error) {
        console.error('Failed to fetch cooperatives:', error);
    }
};

const fetchUsers = async () => {
    try {
        // STORE_OWNER may only see STORE_MANAGER descendants as eligible additional managers.
        const payload = isStoreOwner.value ? { type: 'store manager' } : {};
        const response = await axios.post('/admin/user/list/numbers/hash', payload);
        if (response.data && Array.isArray(response.data)) {
            users.value = response.data;
        }
    } catch (error) {
        console.error('Failed to fetch users:', error);
    }
};

const hasManagerCandidates = computed(() => users.value.length > 0);

const isButtonDisabled = computed(() => {
    return !!(loading.value || successMessage.value || !storeName.value || !description.value || !address.value);
});

const dropzoneRef = ref(null);
const dropzoneFiles = ref([]);

// Watch for new files in dropzone and upload them
watch(() => dropzoneFiles.value, async (newFiles, oldFiles) => {
    // Find files that are not yet uploading and don't have a hashkey
    const filesToUpload = newFiles.filter(f => !f.uploading && !f.hashkey && !f.error);
    
    for (const fileObj of filesToUpload) {
        const index = newFiles.indexOf(fileObj);
        if (index === -1) continue;

        // Set uploading status
        dropzoneRef.value.setFileStatus(index, { uploading: true, progress: 30 });
        
        const result = await uploadFile(fileObj.file);
        
        if (result && result.hashkey) {
            dropzoneRef.value.setFileStatus(index, { 
                uploading: false, 
                progress: 100, 
                hashkey: result.hashkey 
            });
        } else {
            dropzoneRef.value.setFileStatus(index, { 
                uploading: false, 
                progress: 0, 
                error: 'Upload failed' 
            });
        }
    }
}, { deep: true });

const handlePhotoRemoved = (hashkey) => {
    removeHash(hashkey);
};

const handleSubmit = async () => {
    error.value = null;
    successMessage.value = '';
    
    if (!storeName.value || !description.value || !address.value) {
        error.value = 'Please fill in all required fields';
        return;
    }

    loading.value = true;
    try {
        const payload = {
            name: storeName.value,
            description: description.value,
            address: address.value,
            category: category.value,
            subcategory: subcategory.value,
            managers: managers.value,
            photourl: dropzoneFiles.value
                .filter(f => f.hashkey)
                .map(f => f.hashkey),
        };

        if (!isStoreOwner.value) {
            payload.owner = owner.value || undefined;
            payload.cooperatives = cooperatives.value;
            payload.status = status.value;
            payload.remarks = remarks.value;
        }

        const response = await axios.post('/Store/New', payload);

        if (response.data && response.data.success) {
            showSuccessState.value = true;
            showSuccessAnimation.value = true;
            successMessage.value = 'Store created successfully!';
            
            // Proactively prefetch stores list so ListStores shows fresh data immediately
            try {
                const listResp = await axios.post('/ListStores/List/data', {});
                if (listResp.data) {
                    const fresh = listResp.data.props || listResp.data;
                    prefetchStore.setCache('POST:/ListStores/List/data:{}', fresh);
                }
            } catch (e) {
                console.warn('Failed to prefetch stores list:', e);
            }
            
            const newStoreHash = response.data.hashkey;
            setTimeout(() => {
                if (newStoreHash) {
                    navigate({ page: 'AddProductsToStore', props: { target: newStoreHash } });
                } else {
                    navigate({ page: 'ListStores' });
                }
            }, 1500);
        } else {
            error.value = response.data?.message || 'Failed to create store';
        }
    } catch (err) {
        console.error('Failed to create store:', err);
        error.value = err.response?.data?.message || 'Failed to create store. Please try again.';
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    fetchUsers();
    fetchCategories();
    if (!isStoreOwner.value) {
        fetchCooperatives();
    }
});
</script>

<template>
    <div class="create-store-page pb-5">
        <div class="tf-container mt-5 mb-4 text-center">
            <h1 class="fw_8 premium-title">Launch Your Store</h1>
            <p class="text-muted">Set up your marketplace presence in just a few clicks</p>
        </div>

        <div v-if="successMessage" class="tf-container mb-4">
            <div class="glass-alert alert-success animate-fade-in">
                <i class="fas fa-check-circle me-2"></i>
                {{ successMessage }}
            </div>
        </div>

        <div v-if="error" class="tf-container mb-4">
            <div class="glass-alert alert-danger animate-shake">
                <i class="fas fa-exclamation-triangle me-2"></i>
                {{ error }}
            </div>
        </div>

        <div class="tf-container">
            <div class="form-grid">
                <!-- Left Column: Basic Info -->
                <div class="form-section">
                    <CardSimple title="Essential Information">
                        <div class="premium-input-group mb-4">
                            <label for="storeName" class="form-label">Store Name <span class="required">*</span></label>
                            <input 
                                type="text" 
                                id="storeName"
                                v-model="storeName"
                                class="premium-input"
                                placeholder="e.g., Organic Bounty Farm"
                                autocomplete="off"
                            >
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="premium-input-group mb-4">
                                    <label for="category" class="form-label">Category</label>
                                    <select 
                                        id="category"
                                        v-model="category"
                                        class="premium-select"
                                        @change="handleCategoryChange"
                                    >
                                        <option value="" disabled>Select a category</option>
                                        <option v-for="cat in categories" :key="cat.value" :value="cat.value">
                                            {{ cat.label }}
                                        </option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="premium-input-group mb-4">
                                    <label for="subcategory" class="form-label">Subcategory</label>
                                    <select 
                                        id="subcategory"
                                        v-model="subcategory"
                                        class="premium-select"
                                        :disabled="subcategories.length === 0"
                                    >
                                        <option value="" disabled>Select subcategory</option>
                                        <option v-for="sub in subcategories" :key="sub.value" :value="sub.value">
                                            {{ sub.label }}
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="premium-input-group mb-4">
                            <label for="description" class="form-label">Description <span class="required">*</span></label>
                            <textarea 
                                id="description"
                                v-model="description"
                                class="premium-input"
                                rows="5"
                                placeholder="Describe what makes your store special..."
                            ></textarea>
                        </div>

                        <div v-if="!isStoreOwner" class="premium-input-group mb-4">
                            <label for="remarks" class="form-label">Internal Remarks</label>
                            <textarea
                                id="remarks"
                                v-model="remarks"
                                class="premium-input"
                                rows="2"
                                placeholder="Any internal notes or remarks..."
                            ></textarea>
                        </div>
                    </CardSimple>
                </div>

                <!-- Right Column: Location & Photos -->
                <div class="form-section">
                    <CardSimple title="Location & Visuals">
                        <div class="premium-input-group mb-4">
                            <label for="address" class="form-label">Address <span class="required">*</span></label>
                            <textarea 
                                id="address"
                                v-model="address"
                                class="premium-input"
                                rows="2"
                                placeholder="Complete physical address"
                            ></textarea>
                        </div>

                        <div v-if="!isStoreOwner" class="row">
                            <div class="col-md-6">
                                <div class="premium-input-group mb-4">
                                    <label for="owner" class="form-label">Store Owner</label>
                                    <select
                                        id="owner"
                                        v-model="owner"
                                        class="premium-select"
                                    >
                                        <option value="" disabled>Select owner</option>
                                        <option v-for="user in users" :key="user.hashkey" :value="user.hashkey">
                                            {{ user.name }} ({{ user.username }})
                                        </option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div v-if="isStoreOwner" class="premium-input-group mb-4">
                            <label class="form-label">Store Owner</label>
                            <div class="premium-input" style="background:rgba(59,130,246,0.06); border-color:rgba(59,130,246,0.25);">
                                <i class="fas fa-user-shield me-2 text-primary"></i>
                                You will be the owner of this store.
                            </div>
                        </div>

                        <!-- Multi-Manager Selection -->
                        <div v-if="!isStoreOwner || hasManagerCandidates" class="premium-input-group mb-4">
                            <label class="form-label">Additional Store Managers</label>
                            <div class="multi-user-list glass-card p-3">
                                <div class="search-box mb-2">
                                    <input type="text" v-model="userSearch" placeholder="Search users..." class="search-input">
                                </div>
                                <div class="user-selection-area">
                                    <div v-for="user in filteredUsers" :key="user.hashkey" class="user-item">
                                        <label class="custom-checkbox-label">
                                            <input type="checkbox" v-model="managers" :value="user.hashkey" class="custom-checkbox">
                                            <span class="user-name">{{ user.name }}</span>
                                            <span class="user-meta">{{ user.username }}</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <p class="input-hint mt-2">Select one or more users to help manage this store.</p>
                        </div>

                        <!-- Cooperative Links (optional, many-to-many) -->
                        <div v-if="!isStoreOwner" class="premium-input-group mb-4">
                            <label class="form-label">Linked Cooperatives</label>
                            <div class="multi-user-list glass-card p-3">
                                <div class="search-box mb-2">
                                    <input type="text" v-model="cooperativeSearch" placeholder="Search cooperatives..." class="search-input">
                                </div>
                                <div class="user-selection-area">
                                    <div v-if="filteredCooperatives.length === 0" class="text-muted small p-2">
                                        No cooperatives available.
                                    </div>
                                    <div v-for="coop in filteredCooperatives" :key="coop.hashkey" class="user-item">
                                        <label class="custom-checkbox-label">
                                            <input type="checkbox" v-model="cooperatives" :value="coop.hashkey" class="custom-checkbox">
                                            <span class="user-name">{{ coop.name }}</span>
                                            <span class="user-meta">{{ coop.cooperative_type || '' }}</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <p class="input-hint mt-2">Optional. Link this store to one or more cooperatives.</p>
                        </div>

                        <div v-if="!isStoreOwner" class="premium-input-group mb-4">
                            <label for="status" class="form-label">Store Status</label>
                            <select 
                                id="status"
                                v-model="status"
                                class="premium-select"
                            >
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="pending">Pending</option>
                                <option value="suspended">Suspended</option>
                            </select>
                        </div>

                        <div class="premium-input-group mb-2">
                            <label class="form-label">Store Photos</label>
                            <Dropzone 
                                ref="dropzoneRef"
                                v-model:files="dropzoneFiles" 
                                @removed="handlePhotoRemoved"
                            />
                            <p class="input-hint mt-2">Upload high-quality images to attract more customers.</p>
                        </div>
                    </CardSimple>
                </div>
            </div>

            <div class="action-bar mt-5 text-center">
                <AnimatedButton 
                    @click="handleSubmit"
                    :disabled="isButtonDisabled"
                    btnClass="btn-premium-launch"
                    :loading="loading"
                    :success="showSuccessState"
                >
                    Create Store Now
                </AnimatedButton>
                
                <div class="mt-4">
                    <button 
                        @click="navigate({ page: 'ListStores' })"
                        class="btn-text"
                    >
                        <i class="fas fa-chevron-left me-2"></i> Cancel and Return
                    </button>
                </div>
            </div>
        </div>

    <!-- Success Animation Overlay -->
    <div v-if="showSuccessAnimation" class="success-overlay">
        <div class="text-center animate-bounce-in">
            <LottiePlayer 
                path="https://cdn.jsdelivr.net/gh/telemagnadon/obj-vault-3a@v2026.05.14-vendor-2/a/11999b7bb57c.json" 
                :loop="false" 
                width="250px" 
                height="250px" 
            />
            <h2 class="fw_8 mt-4 text-primary headline-gradient">Congratulations!</h2>
            <p class="text-muted">Your store is now ready for business.</p>
        </div>
    </div>
  </div>
</template>


<style scoped>
.premium-title {
    font-family: 'Outfit', sans-serif;
    background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: -0.02em;
}

.multi-user-list {
    max-height: 250px;
    overflow-y: auto;
    border: 1px solid rgba(0,0,0,0.08);
    border-radius: 12px;
}

.search-input {
    width: 100%;
    padding: 8px 12px;
    border-radius: 8px;
    border: 1px solid rgba(0,0,0,0.1);
    background: rgba(255,255,255,0.5);
}

.user-item {
    padding: 6px 0;
    border-bottom: 1px solid rgba(0,0,0,0.03);
}

.custom-checkbox-label {
    display: flex;
    align-items: center;
    cursor: pointer;
    gap: 10px;
    width: 100%;
}

.user-name {
    font-weight: 500;
}

.user-meta {
    font-size: 12px;
    color: #64748b;
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
}

@media (max-width: 992px) {
    .form-grid {
        grid-template-columns: 1fr;
    }
}

.premium-input-group {
    display: flex;
    flex-direction: column;
}

.form-label {
    font-weight: 600;
    font-size: 0.9rem;
    color: #475569;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
}

.required {
    color: #ef4444;
    margin-left: 4px;
}

.premium-input, .premium-select {
    padding: 12px 16px;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
    background: #fff;
    font-size: 0.95rem;
    transition: all 0.2s;
    outline: none;
}

.premium-input:focus, .premium-select:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
}

.premium-select {
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2364748b'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 12px center;
    background-size: 16px;
}

.input-hint {
    font-size: 0.8rem;
    color: #94a3b8;
}

.glass-alert {
    padding: 16px 20px;
    border-radius: 16px;
    backdrop-filter: blur(8px);
    font-weight: 500;
    display: flex;
    align-items: center;
}

.alert-success {
    background: rgba(34, 197, 94, 0.1);
    border: 1px solid rgba(34, 197, 94, 0.2);
    color: #15803d;
}

.alert-danger {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.2);
    color: #b91c1c;
}

.btn-premium-launch {
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    color: white;
    border: none;
    padding: 16px 48px;
    border-radius: 14px;
    font-weight: 700;
    font-size: 1.1rem;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.3);
}

.btn-premium-launch:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 20px 25px -5px rgba(37, 99, 235, 0.4);
    filter: brightness(1.1);
}

.btn-premium-launch:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
    box-shadow: none;
}

.btn-loading {
    padding: 12px 48px;
    background: #3b82f6;
}

.btn-text {
    background: transparent;
    border: none;
    color: #64748b;
    font-weight: 500;
    cursor: pointer;
    transition: color 0.2s;
}

.btn-text:hover {
    color: #1e293b;
}

.animate-fade-in {
    animation: fadeIn 0.5s ease-out;
}

.animate-shake {
    animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

@keyframes shake {
    10%, 90% { transform: translate3d(-1px, 0, 0); }
    20%, 80% { transform: translate3d(2px, 0, 0); }
    30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
    40%, 60% { transform: translate3d(4px, 0, 0); }
}

:global(.dark-mode) .premium-input, :global(.dark-mode) .premium-select {
    background: #1e293b;
    border-color: #334155;
    color: #f8fafc;
}

:global(.dark-mode) .premium-title {
    background: linear-gradient(135deg, #f8fafc 0%, #cbd5e1 100%);
    -webkit-background-clip: text;
    background-clip: text;
}

:global(.dark-mode) .form-label {
    color: #94a3b8;
}

.success-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.98);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  backdrop-filter: blur(15px);
}

:global(.dark-mode) .success-overlay {
  background: rgba(18, 20, 24, 0.98);
}

.animate-bounce-in {
  animation: bounce-in 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

@keyframes bounce-in {
  0% { transform: scale(0.3); opacity: 0; }
  50% { transform: scale(1.05); opacity: 1; }
  70% { transform: scale(0.9); }
  100% { transform: scale(1); }
}

.headline-gradient {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}
</style>