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

import { ref, computed, onMounted, watch } from 'vue';
import axios from 'axios';
import { useNavigate } from '../composables/Core/useNavigate.js';
import LoadingSpinner from '../Components/LoadingSpinner.vue';
import CardSimple from '../Components/Core/CardSimple.vue';
import Dropzone from '../Components/Core/Dropzone.vue';
import InputGroup from '../Components/Core/Forms/InputGroup.vue';
import InputGroupSelect from '../Components/Core/Forms/InputGroupSelect.vue';
import InputGroupButton from '../Components/Core/Forms/InputGroupButton.vue';
import InputGroupTextarea from '../Components/Core/Forms/InputGroupTextarea.vue';
import InputGroupCheckbox from '../Components/Core/Forms/InputGroupCheckbox.vue';
import { useFileUpload } from '../composables/useFileUpload.js';
import { usePrefetchStore } from '../stores/prefetch';

const prefetchStore = usePrefetchStore();

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

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

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

const users = ref([]);
const userSearch = ref('');
const categories = 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 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 {
        const response = await axios.post('/admin/user/list/numbers/hash', {});
        if (response.data && Array.isArray(response.data)) {
            users.value = response.data;
        }
    } catch (error) {
        console.error('Failed to fetch users:', error);
    }
};

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 fetchStoreData = async () => {
    const urlParams = new URLSearchParams(window.location.search);
    const hashkey = props.target || urlParams.get('hashkey') || urlParams.get('id');
    
    if (!hashkey) {
        error.value = 'Store ID is missing';
        return;
    }
    
    storeId.value = hashkey;
    loading.value = true;
    try {
        const response = await axios.post('/Edit/Store/Details/data', { target: hashkey });
        if (response.data) {
            const data = response.data;
            storeName.value = data.name || '';
            description.value = data.description || '';
            category.value = data.category || '';
            subcategory.value = data.subcategory || '';
            address.value = data.address || '';
            owner.value = data.owner_hashkey || '';
            status.value = data.status || 'active';
            remarks.value = data.remarks || '';
            managers.value = data.managers_hashkeys || [];
            cooperatives.value = data.cooperative_hashkeys || [];
            
            // Load subcategories for initial category
            if (category.value) {
                await fetchSubcategories();
                subcategory.value = data.subcategory || '';
            }
            
            // Set initial photos in dropzone
            if (data.photourlDropzone && Array.isArray(data.photourlDropzone)) {
                // Dropzone component handles initial files via v-model:files
                const initialFiles = data.photourlDropzone.map(f => ({
                    file: { name: f.name || 'Image' },
                    hashkey: f.hashkey,
                    progress: 100,
                    uploading: false,
                    preview: f.url // Assuming url is provided for preview
                }));
                dropzoneFiles.value = initialFiles;
                
                // Also update the file upload composable state
                setInitialHashes(data.photourlDropzone.map(f => f.hashkey));
            }
        }
    } catch (err) {
        console.error('Failed to fetch store data:', err);
        error.value = 'Failed to load store data';
    } finally {
        loading.value = false;
    }
};

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

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

// Logic moved to Dropzone component and its v-model

// Watch for new files in dropzone and upload them
watch(() => dropzoneFiles.value, async (newFiles) => {
    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;

        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 response = await axios.post('/Store/Edit', {
            target: storeId.value,
            name: storeName.value,
            description: description.value,
            address: address.value,
            category: category.value,
            subcategory: subcategory.value,
            owner: owner.value || undefined,
            managers: managers.value,
            cooperatives: cooperatives.value,
            status: status.value,
            remarks: remarks.value,
            photourl: dropzoneFiles.value
                .filter(f => f.hashkey)
                .map(f => f.hashkey)
        });

        if (response.data && response.data.success) {
            successMessage.value = 'Store updated 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);
            }
            
            setTimeout(() => {
                navigate({ page: 'ViewStoreMarket', props: { target: storeId.value } });
            }, 1500);
        } else {
            error.value = response.data?.message || 'Failed to update store';
        }
    } catch (err) {
        console.error('Failed to update store:', err);
        error.value = err.response?.data?.message || 'Failed to update store. Please try again.';
    } finally {
        loading.value = false;
    }
};

onMounted(async () => {
    await Promise.all([
        fetchUsers(),
        fetchCategories(),
        fetchCooperatives(),
        fetchStoreData()
    ]);
});
</script>

<template>
    <div class="edit-store-page pb-5">
        <div class="tf-container mt-5 mb-4 text-center">
            <h1 class="fw_8 premium-title">Edit Your Store</h1>
            <p class="text-muted">Update your store information and visuals</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">
                        <InputGroup
                            id="storeName"
                            label="Store Name"
                            v-model="storeName"
                            required
                            placeholder="Enter store name"
                        />

                        <div class="row">
                            <div class="col-md-6">
                                <InputGroupSelect
                                    id="category"
                                    label="Category"
                                    v-model="category"
                                    :options="categories.map(c => ({ value: c.value, text: c.label }))"
                                    placeholder="Select a category"
                                    @update:modelValue="handleCategoryChange"
                                />
                            </div>
                            <div class="col-md-6">
                                <InputGroupSelect
                                    id="subcategory"
                                    label="Subcategory"
                                    v-model="subcategory"
                                    :options="subcategories.map(s => ({ value: s.value, text: s.label }))"
                                    placeholder="Select subcategory"
                                    :disabled="subcategories.length === 0"
                                />
                            </div>
                        </div>

                        <InputGroupTextarea
                            id="description"
                            label="Description"
                            v-model="description"
                            required
                            :rows="5"
                            placeholder="Store description..."
                        />

                        <InputGroupTextarea
                            id="remarks"
                            label="Internal Remarks"
                            v-model="remarks"
                            :rows="2"
                            placeholder="Any internal notes or remarks..."
                        />
                    </CardSimple>
                </div>

                <!-- Right Column: Location & Photos -->
                <div class="form-section">
                    <CardSimple title="Location & Visuals">
                        <InputGroupTextarea
                            id="address"
                            label="Address"
                            v-model="address"
                            required
                            :rows="2"
                            placeholder="Store address"
                        />

                        <div class="row">
                            <div class="col-md-6">
                                <InputGroupSelect
                                    id="owner"
                                    label="Store Owner"
                                    v-model="owner"
                                    :options="users.map(u => ({ value: u.hashkey, text: `${u.name} (${u.username})` }))"
                                    placeholder="Select owner"
                                />
                            </div>
                        </div>

                         <!-- Multi-Manager Selection -->
                         <div 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">
                                    <InputGroup
                                        id="userSearch"
                                        v-model="userSearch"
                                        placeholder="Search users..."
                                        variant="soft"
                                        :isPremium="false"
                                    />
                                </div>
                                <div class="user-selection-area">
                                    <div v-for="user in filteredUsers" :key="user.hashkey" class="user-item">
                                        <InputGroupCheckbox
                                            :id="`manager-${user.hashkey}`"
                                            :label="`${user.name} (${user.username})`"
                                            v-model="managers"
                                            :value="user.hashkey"
                                        />
                                    </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 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">
                                    <InputGroup
                                        id="cooperativeSearch"
                                        v-model="cooperativeSearch"
                                        placeholder="Search cooperatives..."
                                        variant="soft"
                                        :isPremium="false"
                                    />
                                </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">
                                        <InputGroupCheckbox
                                            :id="`coop-${coop.hashkey}`"
                                            :label="`${coop.name}${coop.cooperative_type ? ' — ' + coop.cooperative_type : ''}`"
                                            v-model="cooperatives"
                                            :value="coop.hashkey"
                                        />
                                    </div>
                                </div>
                            </div>
                            <p class="input-hint mt-2">Optional. Link this store to one or more cooperatives.</p>
                        </div>

                        <InputGroupSelect
                            id="status"
                            label="Store Status"
                            v-model="status"
                            :options="[
                                { value: 'active', text: 'Active' },
                                { value: 'inactive', text: 'Inactive' },
                                { value: 'pending', text: 'Pending' },
                                { value: 'suspended', text: 'Suspended' }
                            ]"
                        />

                        <div class="premium-input-group mb-2">
                            <label class="form-label">Store Photos</label>
                            <Dropzone 
                                ref="dropzoneRef"
                                v-model:files="dropzoneFiles" 
                                @removed="handlePhotoRemoved"
                            />
                        </div>
                    </CardSimple>
                </div>
            </div>

            <div class="action-bar mt-5 text-center d-flex flex-column align-items-center gap-3">
                <InputGroupButton
                    text="Update Store"
                    :loading="loading"
                    :disabled="isButtonDisabled"
                    size="lg"
                    variant="primary"
                    @click="handleSubmit"
                />
                
                <InputGroupButton
                    text="Cancel and Return"
                    variant="text"
                    @click="navigate({ page: 'ViewStoreMarket', props: { target: storeId } })"
                >
                    <i class="fas fa-chevron-left me-2"></i> Cancel and Return
                </InputGroupButton>
            </div>
        </div>
    </div>
</template>

<style scoped>
:global(.dark-mode) .form-label {
    color: #94a3b8;
}
</style>
